我有一个示例表单,如下所示:
stuff: IStuff;
buildForm() {
this.createForm = this.form.group({
Val1: [{ value: '', disabled: true }],
Val2: [{ value: '', disabled: true }]
});
正如您所看到的,这两个值都设置为禁用。
构造函数触发 httpClient get 并填充模型:
this.exampleHttpService.getStuff()
.subscribe(stuff => this.stuff = stuff);
东西在哪里:
export interface IStuff {
Val1?: number;
Val2?: number
}
Val1 和 Val2 的绑定(bind)在 html 中完成,如下所示:
<input name="Val1" matInput formControlName="Val1" [value]="stuff?.Val1">
这真是太棒了,它很好地分配了值并将它们显示在屏幕上;但是当我尝试使用
恢复这些值时this.createForm.getRawValue()
我得到两个值的“”空字符串...
有什么想法吗?
最佳答案
当您使用响应式(Reactive)表单时,输入值已经绑定(bind)到表单控件,您不需要(也不应该)绑定(bind)到输入的值,因为该值和表单控件不是同一件事。在您的代码中,您正在初始化绑定(bind)到输入值的“东西”,但没有初始化表单控件值。您需要初始化表单控件值:
this.exampleHttpService.getStuff()
.subscribe((stuff) => {
this.createForm.controls['Val1'] = stuff.Val1;
this.createForm.controls['Val2'] = stuff.Val2;
});
关于Angular 6 getRawValue() 将不会返回禁用值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53484088/