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

时间:2017-10-30 06:36:27

标签: angular angular-ngmodel angular4-forms

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

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

这些是我项目的要素:

校类form.component.ts:

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

校类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;
}
.....
}

请帮帮我!

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

你需要先实例化SchoolClass课程,你只有学校课程的参考资料,这个课程目前没有任何意义