angular - 在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.
});
}
}
还有其他更好的设计方法吗?
解决方案
您可以通过映射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。
推荐阅读
- php - 在 PHP 中创建日志文件
- php - 我如何在数组 var_dump 中获取数据查询 cake php?
- bootstrap-4 - 尽管标记有效,但 Bootstrap 4 折叠手风琴不起作用
- full-text-search - Hibernate Search ,更改默认分析器
- common-lisp - 在不使用 COND、IF、WHEN、UNLESS 或 CASE 的情况下检查参数的类型
- matlab - 为超光谱卫星图像创建具有地面实况的训练和测试集
- swift - swift text.draw 方法搞砸了 CGContext
- python - Pandas:计算多列的唯一组合并在新列中写入数量
- node.js - 找不到模块'./routes/
' 同时运行 Docker 映像 - javascript - 如何获得 sendMessage 的访问/许可以将数据从任何网页发送到后台脚本