我有一个带<tr>
<td>Material of Construction</td>
<td>@Html.DropDownListFor(model => model.CorrGroup.cGroup_MatConst, (SelectList)ViewBag.MaterialConstruction)</td>
</tr>
<tr>
<td></td>
<td>Other Materials @Html.TextBox("OtherMaterials", "", new { @class = "mandatoryTextArea", @disabled = "disabled" })</td>
</tr>
的简单Angular 2组件,我将其绑定到模板。模板显示输入数据,但我无法从构造函数访问它:
@Input
这是一个带有示例的plunker(参见“names-component.ts”)。
我做错了什么?
答案 0 :(得分:93)
因为在设置视图之前,Input
属性未初始化。根据{{3}},您可以使用ngOnInit
方法访问您的数据。
import {Component, bootstrap, Input, OnInit} from '@angular/core';
import DataService from './data-service';
@Component({
selector: 'app-cmp',
template: `{{data.firstName}} {{data.lastName}} {{name}}`
})
export default class NamesComponent implements OnInit {
@Input() data;
name: string;
constructor(dataService: DataService) {
this.name = dataService.concatNames("a", "b");
console.log(this.data); // undefined here
}
ngOnInit() {
console.log(this.data); // object here
}
}
答案 1 :(得分:3)
您必须实施OnChanges,见下文:
import {Component, bootstrap, Input, OnChanges} from '@angular/core';
import DataService from './data-service';
@Component({
selector: 'app-cmp',
template: `{{data.firstName}} {{data.lastName}} {{name}}`
})
export default class NamesComponent implements OnChanges {
@Input() data;
name: string;
constructor(dataService: DataService) {
this.name = dataService.concatNames("a", "b");
console.log(this.data); // undefined here
}
ngOnChanges() {
console.log(this.data); // object here
}
}
答案 2 :(得分:0)
The way to access your data per documentation here是写一个setter和一个getter。在这些方法中,您可以操纵对象/数据。看这里:
private _data = '';
@Input()
set data(data: any) {
this._data = data;
}
get data(): string {
console.log(_data) // <-------- you will see your data here
return this._data;
}
}