• Front-end framework Angular8.0
  • NG – ZORRO UI component
  • Scenario: Form input: Dynamically add input fields to the front end

  • Data: eg: [‘123′,’222′,’ XXX ‘][" 192.168.1.127/24 123.2.1.11 ", ""," 123.2.1.11-192.168.1.127 "]
<div *ngFor="let item of ipPoolData['_ipAddress'] index as i; trackBy:trackByFn" style="height: 50px; position: relative;" > < INPUT name="{{'_ipAddress'+ I}}" NZ-input type="text" placeholder=" Please input IP/ subnet IP/ subnet range "required [(ngModel)]="ipPoolData['_ipAddress'][i]" (ngModelChange)="checkIpRangeVal($event)"> <span *ngIf="error['iprange']" Class ="text-error"> </span> <div class=" bTN-handle-item "> <button nZ-button nzType="danger" [nzSize]="'small'" (click)="deleteIPCollectionField(i)" *ngIf="ipPoolData['_ipAddress'].length>1"> <i nz-icon nzType="minus" nzTheme="outline"></i> </button> <button *ngIf="item && ipPoolData['_ipAddress'].length < 5" nz-button nzType="primary" [nzSize]="'small'" [disabled]="ipPoolData['_ipAddress'].length-1 > i " (click)="addIPCollectionField()"> <i nz-icon nzType="plus" nzTheme="outline"></i> </button> </div> </div>Copy the code

Pit 1:

  • Question:When each item of the array is of string type, ngModel in the input is directly bound with item after the loop, and ngModle cannot be assigned
  • Ngmodel: ipPoolData[‘_ipAdress’][I] : ipPoolData[‘_ipAdress’][I] : ipPoolData[‘_ipAdress’][I]

Pit 2:

  • Question:Input The mouse will be out of focus for every character entered.
  • Reason: After ngModel is bound with ipPoolData[‘_ipAdress’][I], Angular requeries the server to reset the list of all new item objects after each input, even if the items were previously displayed. In this case, Angular only sees a new list of new object references and has no choice but to replace the old DOM elements with all the new ONES. Therefore, the mouse will lose focus for every character input.
  • Solution:
<div *ngFor="let item of ipPoolData['_ipAddress'] index as i; trackBy:trackByFn"></div>Copy the code

TrackBy: trackByFn; Add a method to this component that returns the value NgFor should track. In this case, the value is the I entry of ipPoolData[‘_ipAdress’]. If the index entry of ipPoolData[‘_ipAdress’] is already rendered, Angular tracks it. The same ipPoolData[‘_ipAdress’] index is not queried again.

trackByFn(index: any, item: any) {   
    return index;  
}
Copy the code