Angular - formGroupName 值更改不会更新表单 [英] Angular - formGroupName value change does not update the form
问题描述
如标题所述,formGroupName
值更改不会更新表单.(点击按钮后,输入中显示的值保持不变)
这是一个plunker.
@Component({选择器:'我的应用',模板:`<form [formGroup]="myForm"><div [formGroupName]="fgn"><input [formControlName]="'name'">
</表单><button(点击)="formChange()" >Change</button>{{fgn}}<br>{{myForm.value |json}}`,})出口类应用{私人 myForm:FormGroup;私人 fgn:字符串;ngOnInit() {this.fgn = '零';this.myForm = this.formBuilder.group({零:this.formBuilder.group({名称:'零'}),一:this.formBuilder.group({名称:'一个'})});}表单更改(){this.fgn = '一个';}构造函数(私有表单构建器:FormBuilder){}}
我会推荐喜欢而不是使用,
使用,
</表单>
原因是,如果您有 n 个输入字段,例如,表单中有超过 25 个字段,则应用 [formControl]="myForm.controls[fgn] 不是一个好习惯.control['name']"
在每个字段中进行声明,因为如果您想修改任何简单的更改,这将花费更多时间并且看起来像是一场噩梦.
相反,如果您使用 [formGroup]="myForm.controls[fgn]"
,它将自行处理内部的 [formControlName]
.这很有效,因为我在我的项目中使用它.
感谢@Amit 在我心中发起这个想法.
希望这会有所帮助.快乐的优化编码 :)
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)
Here is a plunker.
@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) {
}
}
I would recommend like instead of using,
<input [formControl]="myForm.controls[fgn].controls['name']">
use,
<form [formGroup]="myForm">
<div [formGroup]="myForm.controls[fgn]">
<input [formControlName]="'name'">
</div>
</form>
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.
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.
Thanks to @Amit for initiating this idea in me.
Hope this helps. Happy optimized coding :)
这篇关于Angular - formGroupName 值更改不会更新表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!