我需要得到所有的字符串包含到赋值数组,这是Atm对象的一个属性,并把他们放在所有的动态输入,一个为每个字符串给机会更新他们或删除。 如何使用FormArray?
null
atm: Atm; //has an array of string as property
get Assignes() {
return this.virtualForm.get('Assignes') as FormArray;
}
addAssigne() {
this.Assignes.push(this.formBuilder.group({ point: '' }));
}
deleteAssigne(index) {
this.Assignes.removeAt(index);
}
buildForm() {
this.form = new FormGroup({
model: new FormControl(this.atm.Model , Validators.required),
vendor: new FormControl(this.atm.Vendor , Validators.required),
Assignes : new FormControl(this.atm.Assignes),
}
<div formArrayName="Assignes">
<div *ngFor="let item of Assignes.controls; let pointIndex=index" [formGroupName]="pointIndex">
<mat-form-field appearance="outline">
<mat-label>Assigne</mat-label>
<input matInput formControlName="point" [readonly]=!isAdmin placeholder="Assigne"/>
</mat-form-field>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="deleteAssigne(pointIndex)">Delete assigne</button>
</div>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="addAssigne()">Add assigne</button>
</div>
null
即使不使用FormArray,也可以简单地完成该操作。 您只需要在数组上运行for循环并呈现动态输入字段。
代码应如下所示:
<div *ngFor="let item of atm; let pointIndex=index" >
<mat-form-field appearance="outline">
<mat-label>Assigne</mat-label>
<input matInput name="assigne{{i}}" [(ngModel)]="item" placeholder="Assigne"/>
</mat-form-field>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="deleteAssigne(pointIndex)">Delete assigne</button>
</div>
<button color="primary" *ngIf="isAdmin" mat-raised-button (click)="addAssigne()">Add assigne</button>
。ts文件应由以下人员更新:
atm: Atm; //has an array of string as property
addAssigne() {
this.atm.push('');
}
deleteAssigne(index) {
this.atm.splice(index,1);
}