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

标签 angular null angular-material angular-reactive-forms

我有一个示例表单,如下所示:

 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/

相关文章:

javascript - angular ng-messages 仅在 $touched 为真时显示

javascript - 如何在 Angular Material 自动完成的末尾有一个链接?

angular - 尝试使用具有不同模板的相同组件

Angular 5 展开/折叠列表

angular - 设置 p-dropdown 的滚动高度会引发错误

c++ - 空指针等价于 int

node.js - 在Docker中构建Angular会抛出 “environment.prod.ts path in file replacements does not exist”

sql - 设置变量时,记录的 IS NOT NULL 测试不返回 TRUE

sql - Firebird VARCHAR 中的 NULL 字符

html - 如何在特定索引处的 ngfor 中插入/显示 div