Search code examples
angularangular-ngmodelangular4-forms

I can not access variable through ngModel - Angular 4


I created a form component to use for actions to edit and insert new data, so I created a variable that represents the object in my component and I reference it with [(ngModel)]="schoolClass.name", however the following error appears on the console:

ERROR TypeError: Cannot read property 'name' of null
    at Object.eval [as updateDirectives] (SchoolClassFormComponent.html:5)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13067)
    at checkAndUpdateView (core.es5.js:12251)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)
    at execEmbeddedViewsAction (core.es5.js:12557)
    at checkAndUpdateView (core.es5.js:12252)
    at callViewAction (core.es5.js:12599)
    at execComponentViewsAction (core.es5.js:12531)
    at checkAndUpdateView (core.es5.js:12257)
    at callViewAction (core.es5.js:12599)
    at execEmbeddedViewsAction (core.es5.js:12557

I have already used the following operator [(ngModel)]="schoolClass?.name", but when using it it appears this error:

ZoneAwareError {__zone_symbol__error: Error: Uncaught (in promise): Error: Template parse errors: Parser Error: The '?.' operator cannot b…, …}
message : "Uncaught (in promise): Error: Template parse errors:↵Parser Error: The '?.' operator cannot be used in the assignment at column 19 in [schoolClass?.name=$event] in ng:///SchoolClassModule/SchoolClassFormComponent.html@4:37 ("↵    <div class="row">↵      <div class="input-field col s12">↵        <input type="text" id="name" [ERROR ->][(ngModel)]="schoolClass?.name" name="name" class="validate">↵ ....

These are the elements of my project:

school-class-form.component.ts:

export class SchoolClassFormComponent implements OnInit, OnDestroy {
    schoolClass: SchoolClass;
    .....
}

school-class-form.component.html:

<input type="text" id="name" [(ngModel)]="schoolClass.name" name="name" class="validate">

school-class.ts:

export class SchoolClass {

constructor( 
    private _name : string
) { }

.....

get name() : string {
    return this._name;
}

set name(name : string) {
    this._name = name;
}
.....
}

Help me please!


Solution

  • You only set the type of your schoolClass. You need also to initialize your schoolClass.

    export class SchoolClassFormComponent implements OnInit, OnDestroy {
        schoolClass: SchoolClass = new SchoolClass('Name'); // What name you want
        .....
    }