我无法将angular2传递给子组件。在子组件中,对象始终未定义。这是我的代码。
我在父组件中的标记
import {Component, View, Input} from 'angular2/angular2';
@Component({
selector: 'peoplesearchlist',
inputs: ['people']
})
@View({
templateUrl: './directory/peopleSearchList.html'
})
export class PeopleSearchList {
constructor() {
console.log('People-Search-List:' + this.people);
}
}
子组件
import {Component, View, Input, bootstrap} from 'angular2/angular2';
import {Http, Headers} from 'angular2/http';
import {PeopleSearchBar} from './peopleSearchBar';
import {PeopleSearchList} from './peopleSearchList';
@Component({
selector: "directory-people-search"
})
@View({
templateUrl: "./directory/peopleSearch.html",
directives: [PeopleSearchBar, PeopleSearchList]
})
export class PeopleSearch
{
constructor(http: Http) {
this.searchString = '';
this.http = http;
this.peopleSearchData = {
faculty: [],
students: [],
retirees: []
};
console.log('People-Search' + this.peopleSearchData);
}
}
缩写的父组件
{{1}}
如果我查看我的控制台,我首先看到父组件中包含该对象的日志,然后将子组件中的日志视为未定义。我尝试过使用@Input人,但行为相同。
我正在使用带有traceur的ES6。我查看了这个问题但无法解决我的问题:Angular 2 Component @Input not working
答案 0 :(得分:2)
我知道这个问题已经有9个月了,你可能还是设法自己做了这个问题:
问题在于,您尝试在构造函数中获取组件的值,该构造函数在实例化此组件时调用,但绑定尚未初始化。您需要实现AfterViewInit
接口而不是构造函数:
@Component(...)
export class PeopleSearchList implements AfterViewInit {
constructor() {
}
ngAfterViewInit() {
console.log('People-Search-List:' + this.people);
}
}
答案 1 :(得分:0)
尝试类似的东西,它对我有用:
import {Component, View, Input} from 'angular2/angular2';
@Component({
selector: 'peoplesearchlist'
})
@View({
templateUrl: './directory/peopleSearchList.html'
})
export class PeopleSearchList {
@Input() people: Object
constructor() {
console.log('People-Search-List:' + this.people);
}
}
答案 2 :(得分:0)
使用ngOnChanges()
检测数据何时进入您的输入。
在输入可用之前调用构造函数。
ngOnChanges(): void {
console.log('People-Search-List:' + this.people);
}