【问题标题】:Form builder 'Cannot read property (...) of null'表单生成器“无法读取 null 的属性 (...)”
【发布时间】:2020-04-29 10:10:24
【问题描述】:

Model.ts

class A {
    b: B;
}

class B {
    someValue: string;
}

Component.ts

import { FormBuilder } from '@angular/forms';

this.formInput = this.formBuilder.group({
    'valueController': [this.a.b.someValue],
});

错误

第一次加载页面时显示如下错误:

ERROR TypeError: Cannot read property 'someValue' of null

我正在构建一个表单页面来创建一个实体,其中模型开始为空。我尝试在构造函数中初始化b,但它不起作用。我不想在component.ts 中设置b 的值

我该如何进行这项工作?

【问题讨论】:

    标签: angular formbuilder angular2-formbuilder


    【解决方案1】:

    丹尼尔,我想你有一些喜欢

    this.a=new A()
    

    但是a只是一个空对象,就像你写的一样

    this.a={}
    

    如果你的类有类似的构造函数

    class A {
        b: B;
        constructor()
        {
          this.b=new B()
        }
    }
    
    this.a will be an object with property b, but this.a.b is an empty object too.
    

    只有当你写在B的构造函数中,有些像

    class B {
        someValue: string;
        constructor()
        {
          this.someValue="hello"
        }
    }
    

    你会得到一个有值的对象

    注意:通常在 Angular 中,如果唯一的目标是具有“类型变量”,我们会使用接口,您可以查看文档 about classabout interfaces

    【讨论】:

      猜你喜欢
      • 2018-01-19
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2021-07-16
      相关资源
      最近更新 更多