我在让 angular2 将输入传递到子组件时遇到问题。在子组件内,该对象始终是未定义的。这是我的代码。
我在父组件中的标记
<peoplesearchlist [people]="peopleSearchData"></peoplesearchlist>
子组件
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);
}
}
如果我查看控制台,我首先会看到来自带有对象的父组件的日志,然后看到来自子组件的日志为未定义。我尝试过使用@Input people,但有相同的行为。
我正在使用 ES6 和 Traceur。我已经查看了这个问题,但无法解决我的问题:Angular 2 Component @Input not working
最佳答案
我知道这个问题已经有 9 个月了,您可能已经设法自己解决了:
问题是您试图在构造函数中获取组件的值,该构造函数是在实例化该组件但绑定(bind)尚未初始化时调用的。您需要实现 AfterViewInit
接口(interface)而不是构造函数:
@Component(...)
export class PeopleSearchList implements AfterViewInit {
constructor() {
}
ngAfterViewInit() {
console.log('People-Search-List:' + this.people);
}
}
关于Angular 2 - 组件输入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33919905/