Angular-formGroupName值更改不会更新表单 [英] Angular - formGroupName value change does not update the form
问题描述
如标题中所述,formGroupName
值更改不会更新表格.
(点击按钮后,输入中显示的值保持不变)
As described in the title, formGroupName
value change does not update the form.
(after hitting the button the value displayed in the input remains the same)
这是朋克车.
@Component({
selector: 'my-app',
template: `
<form [formGroup]="myForm">
<div [formGroupName]="fgn">
<input [formControlName]="'name'">
</div>
</form>
<button (click)="formChange()" >Change</button>
{{fgn}}
<br>
{{myForm.value | json}}
`,
})
export class App {
private myForm: FormGroup;
private fgn: String;
ngOnInit() {
this.fgn = 'zero';
this.myForm = this.formBuilder.group({
zero: this.formBuilder.group({
name: 'Zero'
}),
one: this.formBuilder.group({
name: 'One'
})
});
}
formChange() {
this.fgn = 'one';
}
constructor(private formBuilder: FormBuilder) {
}
}
推荐答案
我建议不要使用,
<input [formControl]="myForm.controls[fgn].controls['name']">
使用
<form [formGroup]="myForm">
<div [formGroup]="myForm.controls[fgn]">
<input [formControlName]="'name'">
</div>
</form>
原因是,如果您有n个输入字段,例如,一个表单中有超过25个字段,则在每个字段中应用[formControl]="myForm.controls[fgn].controls['name']"
类型的声明不是一个好习惯,因为这将花费更多时间如果您想修改任何简单的更改,它就像一场噩梦.
The reason is, if you have n number of input fields, for example, more than 25 fields in a form, it is not a good practice to apply [formControl]="myForm.controls[fgn].controls['name']"
kind of declaration in each field as this will take more time and looks like a nightmare if you want to modify any simple changes.
相反,如果您使用[formGroup]="myForm.controls[fgn]"
,它将独自照顾内部的[formControlName]
.当我在项目中使用它时,效果很好.
Instead, if you use [formGroup]="myForm.controls[fgn]"
, it will take care of the inner [formControlName]
by itself. And this works well as I'm using it in my project.
感谢@Amit在我体内发起这个想法.
Thanks to @Amit for initiating this idea in me.
希望这会有所帮助.快乐的优化编码:)
Hope this helps. Happy optimized coding :)
这篇关于Angular-formGroupName值更改不会更新表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!