Search code examples
angularformbuilderangular2-formbuilder

Form builder 'Cannot read property (...) of null'


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

When loading the page for the first time the following error shows:

ERROR TypeError: Cannot read property 'someValue' of null

I'm building a form page to create an entity, where the model starts out empty. I've tried initializing b in the constructor, but it doesn't work. I don't want to set the value of b in the component.ts

How do I make this work?


Solution

  • Daniel, I suppose you has some like

    this.a=new A()
    

    But a is only an empy object , it's like you write

    this.a={}
    

    If your class has a constructor like

    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.
    

    Only if you write in constructor of B, some like

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

    You'll get an object with value

    NOTE: Usually in Angular we use interface if the only aim is has "typed variables", you can see the docs about class or about interfaces