我无法通过 ngModel 访问变量-Angular 4
2017-10-30
592
我创建了一个表单组件,用于编辑和插入新数据的操作,因此我创建了一个表示组件中对象的变量,并使用 [(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">↵ ....
这些是我的项目的元素:
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;
}
.....
}
请帮帮我!
2个回答
您仅设置
schoolClass
的类型。您还需要初始化
schoolClass
。
export class SchoolClassFormComponent implements OnInit, OnDestroy {
schoolClass: SchoolClass = new SchoolClass('Name'); // What name you want
.....
}
Suren Srapyan
2017-10-30
您需要先实例化 SchoolClass 类,您只有学校课程的引用,但该引用当前未指向任何内容
Ibraheem Al-Saady
2017-10-30