Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度窗体-如何为formArrayName中的select绑定formControlName以使用对象_Angular_Angular Reactive Forms_Formgroups - Fatal编程技术网

Angular 角度窗体-如何为formArrayName中的select绑定formControlName以使用对象

Angular 角度窗体-如何为formArrayName中的select绑定formControlName以使用对象,angular,angular-reactive-forms,formgroups,Angular,Angular Reactive Forms,Formgroups,我试图弄清楚如何在FormarAyname中为select设置绑定对象复杂绑定。我猜formControlName应该引用数组中的当前项,但我不知道如何访问它 <div formArrayName="users"> <div *ngFor="let u of users.controls; let i=index" [formGroupName]='i'> user {{i}}: <select formControlName='id'[comp

我试图弄清楚如何在FormarAyname中为
select
设置绑定对象复杂绑定。我猜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>

编辑:根据OP的意愿,我们希望将对象保留为select中的值,因此我们可以不在formarray中使用formgroup,只需按下formcontrols,其中包含对象值:

this.group.users.forEach(u=>{
this.users.push(this.fb.control(u))//只需按formcontrol!
});
然后在模板中标记:


{{a.login}
由于我们现在使用对象值作为formcontrol,因此在尝试匹配预设值时,我们需要一个compareWith函数:

compareFn(a,b):布尔型{
返回a.id==b.id;
}


原始答案:

我可能会在选择更改时调用一个函数,然后从
availableUsers
中查找用户,并使用找到的用户设置
login
的表单值。So模板:


{{a.login}
因此,您可以删除与比较的
,因为我们现在使用一个数字作为值。然后是
findLogin
函数,我们在其中传递迭代中的当前formgroup:

findLogin(组:FormGroup){
const user=this.availableUsers.find(x=>x.id===group.get('id').value)
group.get('login').setValue(user.login);
}

您好,感谢您提供的解决方案,但我希望在不复制更改事件中的数据的情况下对其进行存档。如果设置ngValue=“a”,则在
选项中已经有了整个对象,我希望重用它。在我的应用程序中,我需要支持一个非常复杂的用户模型,我希望在开始时删除所有未来的维护,并为此提供“愚蠢的简单解决方案”。@igby,我看到的一个选项是,不是将formgroups推送到数组中,而是表单控件(它当时是一个对象)。然后,您需要一个带有
功能的
比较。这是一个选择:根据具体情况,也许这对你有用?是的!这就是我搜索的确切设置。我甚至理解我的错误:D非常感谢!太好了,很高兴听到它适合你!更新的答案也反映了未来读者的选择:)
   <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;
  }