Angular 6 getRawValue() 将不会返回禁用值

问题描述 投票:0回答:4

我有一个示例表格如下:

 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 的绑定是在 html 中完成的,如下所示:

  <input name="Val1" matInput formControlName="Val1" [value]="stuff?.Val1">

这真是太棒了,它很好地分配了值并将它们显示在屏幕上;但是当我尝试使用

恢复这些值时
this.createForm.getRawValue()

我得到两个值的“”空字符串...

有什么想法吗?

angular null angular-material angular-reactive-forms
4个回答
1
投票

当您使用反应式表单时,输入值已经绑定到表单控件,您不需要(也不应该)绑定到输入的值,因为该值和表单控件不是同一件事。在您的代码中,您正在初始化绑定到输入值的“东西”,但没有初始化表单控件值。您需要初始化表单控件值:

this.exampleHttpService.getStuff()
    .subscribe((stuff) => {
        this.createForm.controls['Val1'] = stuff.Val1;
        this.createForm.controls['Val2'] = stuff.Val2;
    }); 

1
投票

从服务取回数据后,是否在 FormControls 上设置值?从我看到的代码中,您将 FormControls 初始化为空字符串,因此我猜测您可能没有设置值?


0
投票

初始化响应式表单的正确方法是:

stuff: IStuff; 
 buildForm() {
        //Get value for stuff before initializing form
        this.createForm = this.form.group({
            Val1: [{ stuff.Val1: '', disabled: true }],
            Val2: [{ stuff.Val2: '', disabled: true }]
        });

这里另一个值得注意的点是,为了获取表单的值,

this.createForm.value
不会为禁用的控件提供更新的值。
this.createForm.getRawValue()
是这种情况下的选择。


0
投票

上述代码中的问题是您正在初始化表单,但没有将值绑定到表单。相反,您可以使用属性绑定将值绑定到模板,而不是将值绑定到表单本身。

如果您使用反应式表单,请始终绑定您的数据并使用表单本身更新您的数据。

this.exampleHttpService.getStuff()
    .subscribe((stuff) => {
        this.createForm.get('Val1').setValue(stuff.Val1);
        this.createForm.get('Val2').setValue(stuff.Val2);
    }); 

或者

this.exampleHttpService.getStuff()
        .subscribe((stuff) => {
            this.createForm.get('Val1').patchValue({
               Val1: stuff.Val1
               val2: stuff.Val2
             });
           
        }); 

表单的 getRawValue()value 之间的区别是 getRawValue() 获取所有字段数据,值仅获取启用的字段(禁用将从对象中删除)

© www.soinside.com 2019 - 2024. All rights reserved.