我试图弄清楚如何为select
formArrayName 内部设置绑定对象复杂绑定。我猜测 formControlName 应该引用数组中的当前项,但我不知道如何访问它。
<div formArrayName="users">
<div *ngFor="let u of users.controls; let i=index" [formGroupName]='i'>
user {{i}}: <select formControlName='id'[compareWith]="compareFn">
<option *ngFor="let a of avaliableUsers" [ngValue]='a'>{{a.login}}</option>
</select>
</div>
</div>
我已经创建了带有单选(按我想要的方式工作)和将值推入“id”的数组的演示。 https://stackblitz.com/edit/angular-d2uaa1
任何帮助是极大的赞赏。
编辑
关键点:
UsersGroup
使用所有属性(id 和登录名)绑定整个对象- 最低附加代码 (KISS)
解决方案(基于@JT_82 评论)
<div *ngFor="let u of users.controls; let i=index">
<select [formControlName]='i' [compareWith]="compareFn">
<option *ngFor="let a of avaliableUsers" [ngValue]='a'>{{a.login}}</option>
</select>
</div>
ngOnInit(): void {
this.owner.patchValue(this.group.owner);
this.group.users.forEach(u => {
this.users.push(this.fb.control(u))
});
}
compareFn(a, b): boolean {
return a.id === b.id;
}