在Angular 6中将默认值设置为formArray [英] Set default values to formArray in Angular 6

查看:75
本文介绍了在Angular 6中将默认值设置为formArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

联系方式

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

Contact组件,使用值初始化的contact数组,

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?

推荐答案

您可以映射 contacts ,并将 contacts 中的每个元素转换为 FormGroup ,并将其设置为您的联系人 FormArray 的一部分.

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.

要将 contact 转换为 Contact FormGroup ,您只需将 contact 对象作为arg传递给一个将使用这些值并将其设置为控件的默认值的函数.

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.

尝试一下:

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 供您参考.

Here's a Sample StackBlitz for your ref.

这篇关于在Angular 6中将默认值设置为formArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆