Angular 8: 如何将 formControlName 与 FormArray 一起使用
Angular 8: How to use formControlName with FormArray
如何将 formControlName
映射到特定的 formArray
项目?
我无法控制服务器数据并尝试使用 phone 数字数组创建表单。
表单本身在视觉上并没有将 phone 并排布置,我希望能够像通常使用 formGroup 那样声明 phone 的输入控件。
到目前为止我有以下内容:
控制器:
const exampleData = {
'name': 'John Doe',
'phones': [
{
'type': 'home',
'number': '5555555'
},
{
'type': 'cell',
'number': '5555555'
}
]
};
this.form = this.fb.group({
name:[],
phones: this.fb.array([
this.fb.group({
type: '',
number: []
}),
this.fb.group({
type: '',
number: []
})
]),
});
this.form.patchValue(exampleData);
模板
<input type="text" formControlName="name">
<!-- This works but I need to loop -->
<div formArrayName="phones">
<div *ngFor="let phone of form.get('phones').controls; let i = index">
<div [formGroupName]="i">
<label>Type: </label><input formControlName="type"/>
<label>Number: </label><input formControlName="number"/>
</div>
</div>
</div>
<!-- How can I point to a phone directly? -->
<input type="text" formControlName="point to type home's number...with helper function or something...">
看看这是否可行?
我通过 运行 setValue
再次解决这个问题,这就是为什么同一个表单控件的任何输入都会更新,当我们在数据流中使用 ngModel 时,这就像双向数据绑定到即时和其他控件。
此方法将创建 formGroup
getPhoneGroup() {
const form = this.fb.group({
type: '',
num: []
});
const elm = form.get('num');
elm.valueChanges.subscribe(val => {
elm.setValue(val, { emitEvent: false })
});
return form;
}
试试这个来访问 formArray 项目:
<div [formGroup]="form.get('phones').at(1)">
<input type="text" formControlName="num">
</div>
如何将 formControlName
映射到特定的 formArray
项目?
我无法控制服务器数据并尝试使用 phone 数字数组创建表单。
表单本身在视觉上并没有将 phone 并排布置,我希望能够像通常使用 formGroup 那样声明 phone 的输入控件。
到目前为止我有以下内容:
控制器:
const exampleData = {
'name': 'John Doe',
'phones': [
{
'type': 'home',
'number': '5555555'
},
{
'type': 'cell',
'number': '5555555'
}
]
};
this.form = this.fb.group({
name:[],
phones: this.fb.array([
this.fb.group({
type: '',
number: []
}),
this.fb.group({
type: '',
number: []
})
]),
});
this.form.patchValue(exampleData);
模板
<input type="text" formControlName="name">
<!-- This works but I need to loop -->
<div formArrayName="phones">
<div *ngFor="let phone of form.get('phones').controls; let i = index">
<div [formGroupName]="i">
<label>Type: </label><input formControlName="type"/>
<label>Number: </label><input formControlName="number"/>
</div>
</div>
</div>
<!-- How can I point to a phone directly? -->
<input type="text" formControlName="point to type home's number...with helper function or something...">
看看这是否可行?
我通过 运行 setValue
再次解决这个问题,这就是为什么同一个表单控件的任何输入都会更新,当我们在数据流中使用 ngModel 时,这就像双向数据绑定到即时和其他控件。
此方法将创建 formGroup
getPhoneGroup() {
const form = this.fb.group({
type: '',
num: []
});
const elm = form.get('num');
elm.valueChanges.subscribe(val => {
elm.setValue(val, { emitEvent: false })
});
return form;
}
试试这个来访问 formArray 项目:
<div [formGroup]="form.get('phones').at(1)">
<input type="text" formControlName="num">
</div>