Angular Form数组重复字段问题



我有两个问题:

1( 所有选择框中都显示相同的值2( 点击添加,添加了两个选择框,我只想添加一个

我已在上上传了一个演示https://stackblitz.com/edit/angular-ngxs-select-form-solved

https://stackblitz.com/edit/angular-ngxs-select-form-solved-rnz3hz试试这个。

您必须将值添加到formControl而不是ngModel,来自ngModel的值不会反映在使用formControlName的绑定中。

在动态生成的输入中使用formControlName的绑定:

<div formArrayName="userTechnologies">
<!-- loop throught units -->
<div *ngFor="let unit of form['controls'].userTechnologies['controls']; let i = index ">
<!-- row divider show for every nex row exclude if first row -->
<div *ngIf="form['controls'].userTechnologies['controls'].length > 1 && i > 0">
<hr>
</div>
<div [formGroupName]="i">
<div class="form-group">
<label>Technologies</label>
<select class="form-control" formControlName="user_technology">
<option value="">Select Technology</option>
<option *ngFor="let technology of technologies | async" [value]="technology.id">
{{technology.name}}
</option>
</select>
<div *ngIf="unit['controls'].user_technology.invalid" class="alert alert-danger">
<div *ngIf="unit['controls'].user_technology.errors.required">
Technology is required.
</div>
</div>
</div>
<button class="btn btn-danger" *ngIf="form['controls'].userTechnologies['controls'].length > 1" (click)="removeTechnology(i)">Delete</button>
</div>
</div>
<button class="btn btn-primary" (click)="addTechnology()">Add</button>
</div>

在您的.ts中,addTechnology应该同时适用于新输入和动态生成的输入,以设置其值

addTechnology(tech = '') {  //<--Edited this
const control = <FormArray>this.form.controls['userTechnologies'];
control.push(this.getTechnology(tech));  //<--Edited this
this.editname = ''; //<--Added this
this.form.controls.userTechnologies.updateValueAndValidity(); //<--Added this
}
getTechnology(tech = '') {
return this.fb.group({
user_technology: [tech, Validators.required] //<--Edited this
});
}

在赋值时,调用addTechnology生成动态控件:

showUser(id) {
this.editdetails$ = this.store.select(UserState.userByIndex)
.pipe(map(filterFn => filterFn(id)));
this.editdetails$.subscribe(response => {
this.edituserarray = [];
this.editid = response.id;
this.editname = response.name;
var technologies = response.technology.split(',');
for (let tech of technologies) {
let newName = {
techno: tech
};
// this.edituserarray.push(newName); //<--- Commented this
this.addTechnology(tech); //<--- Added this
}
})
}

最新更新