我有一个简单的 Angular 2 组件@Input
,我将其绑定到模板。模板显示输入数据,但我无法从构造函数访问它:
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 http://plnkr.co/edit/pOAZQK?p=preview举个例子(参见“names-component.ts”)。
我究竟做错了什么?
因为Input
在设置视图之前,属性不会被初始化。根据docs https://angular.io/guide/lifecycle-hooks,您可以访问您的数据ngOnInit
method.
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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)