首页 > 解决方案 > 在Angular 6中将默认值设置为formArray

问题描述

联系模型,

interface Contact {
  name:string;
  age:number;
}

联系人组件,使用 values 初始化的联系人数组,

export class ContactComponent {

 contacts: Contact[] = [{name:'xyz', age:30}, {name:'abc', age: 25}];
 contactForm: FormGroup;

 constructor(private fb: FormBuilder) {
  this.contactForm = this.fb.group({
   contacts: this.fb.array([this.createContact()])
  });
 }

 createContact(): FormGroup {
    return this.fb.group({
       ???????? - How can initialize values here. 
    });
 }

}

还有其他更好的设计方法吗?

标签: angular

解决方案


您可以通过映射contacts并将每个元素contacts转换为 aFormGroup并将其设置为contacts FormArray.

为了将 acontact转换为 a Contact FormGroup,您可以简单地将contact对象作为 arg 传递给将使用这些值并将它们设置为控件的默认值的函数。

尝试这个:

    contacts: Contact[] = [{
      name: 'xyz',
      age: 30
    }, {
      name: 'abc',
      age: 25
    }];
    contactForm: FormGroup;
    
    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {
      this.contactForm = this.fb.group({
        contacts: this.fb.array(this.contacts.map(contact => this.createContact(contact)))
      });
    
      console.log(this.contactForm.value);
    
    }
    
    createContact(contact): FormGroup {
      return this.fb.group({
        name: [contact.name],
        age: [contact.age]
      });
    }

这是您参考的示例 StackBlitz


推荐阅读