我无法通过 ngModel 访问变量 - Angular 4

I can not access variable through ngModel - Angular 4

我创建了一个表单组件用于编辑和插入新数据的操作,因此我创建了一个代表组件中对象的变量,并使用 [(ngModel)]="schoolClass.name" 引用它,但是控制台上出现以下错误:

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

我已经使用了下面的操作符[(ngModel)]="schoolClass?.name",但是在使用的时候出现了这个错误:

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">↵ ....

这些是我项目的元素:

学校-class-form.component.ts:

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

学校-class-form.component.html:

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

学校-class.ts:

export class SchoolClass {

constructor( 
    private _name : string
) { }

.....

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

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

请帮帮我!

您只设置了schoolClass的类型。您还需要初始化 schoolClass.

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

您需要首先实例化 SchoolClass class,您只有学校的引用 class 目前没有任何指向