Angular2 - 不能访问"输入"从我的控制器/构造 [英] Angular2 - cannot access "Inputs" from my controller/constructor
本文介绍了Angular2 - 不能访问"输入"从我的控制器/构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 @input
,这是我结合到模板一个简单的角2的组成部分。模板显示输入的数据,但我不能从构造函数访问它:
I have a simple Angular 2 component with @Input
, which I bind to the template. The template shows input data, but I cannot access it from the constructor:
import {Component, View, bootstrap, Input} from 'angular2/angular2';
import DataService from './data-service';
@Component({
selector: 'app-cmp'
})
@View({
template: `{{data.firstName}} {{data.lastName}}` //-> shows the correct 'data'
})
export default class NamesComponent {
@Input() data: any;
constructor(dataService: DataService) {
console.log(this.data);//undefined
}
}
下面是一个 plunker 用一个例子(见的名字 - component.ts)。
Here is a plunker with an example (see "names-component.ts").
我在做什么错了?
推荐答案
由于该输入
属性后才进行初始化视图设置。按照 DOC ,您可以在的OnInit
方法。
Because the Input
property isn't initialized until view is set up. According to the doc, you can access your data in onInit
method.
import {Component, View, bootstrap, Input} from 'angular2/angular2';
import DataService from './data-service';
@Component({
selector: 'app-cmp'
})
@View({
template: `{{data.firstName}} {{data.lastName}} {{name}}`
})
export default class NamesComponent {
@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
}
}
这篇关于Angular2 - 不能访问"输入"从我的控制器/构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文