简体   繁体   English

将默认值设置为 Angular 6 中的 formArray

[英]Set default values to formArray in Angular 6

Contact Model,联系方式,

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

Contact component, contacts array initialized with 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. 
    });
 }

}

Any other better way of designing it?还有其他更好的设计方式吗?

You can map through the contacts and transform each element in contacts into a FormGroup and set it as a part of your contacts FormArray .您可以通过地图contacts和变换的每个元素contactsFormGroup并将其设置为你的一部分contacts FormArray

For transforming a contact into a Contact FormGroup you can simply pass the contact object as an arg to a function which will use these values and set them as the default values of the controls. FormGroup contact转换为Contact FormGroup您可以简单地将contact对象作为 arg 传递给一个函数,该函数将使用这些值并将它们设置为控件的默认值。

Try this:尝试这个:

    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]
      });
    }

Here's a Sample StackBlitz for your ref.这是供您参考的示例 StackBlitz

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM