【发布时间】:2017-07-12 08:10:54
【问题描述】:
我有一个 angular 2 反应形式,有四个 formControls,只有一个输入字段。我想要的是要求用户一一填写信息。因此,我将firstControlName 分配给ngOnInit 上的属性调用currentFormControlName,并将其与模板文件中的输入字段绑定。当用户填写他的姓名时,该字段将有效并且在提交时我会将currentFormControlName 属性更改为下一个formControlName。但问题是绑定没有更新。输入字段仍然绑定到name。当我在输入字段中输入内容时,name 的值正在更新,而不是 email。
app.component.ts
ngOnInit() {
this.form = this.builder.group({
'name': ['', Validator.required],
'email': ['', Validator.email],
'phone': ['', Validator.required],
'password': ['', Validator.required],
});
this.currentFormControlName = 'name';
}
submit() {
this.currentFormControlName = 'email'; // Setting it manually just for the demo of this question.
}
app.component.html
<form [formGroup]="form">
<input type="text" [formControlName]="currentFormControlName">
<input type="submit" (click)="submit()">
</form>
【问题讨论】:
-
你尝试过
this.currentFormControlName = this.form.get('name');(并且对邮件使用相同的方法)? -
我不认为这是可能的..每个输入都需要有一个表单控件女巫在表单组的初始化中定义。
-
您可以将 ngSwitch 与 Subject 结合使用,并且每次触发 submit() 时,您都会通过显示 nexy 输入字段来更新表单
标签: angular angular-reactive-forms