我有两个问题:
1)在所有选择框中显示相同的值 2)单击添加时,将添加两个选择框,我只希望添加一个
我已经在https://stackblitz.com/edit/angular-ngxs-select-form-solved上上传了一个演示
答案 0 :(得分:2)
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
}
})
}