gpt4 book ai didi

angular - 在 Angular 6 中将默认值设置为 formArray

转载 作者:行者123 更新时间:2023-12-02 00:28:43 28 4
gpt4 key购买 nike

联系模型,

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

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

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

}

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

最佳答案

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

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

试试这个:

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

这是一个 Sample StackBlitz供您引用。

关于angular - 在 Angular 6 中将默认值设置为 formArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786403/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com