Angular 2 - 组件输入问题

标签 angular

我在让 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/

相关文章:

angular - Angular 8负载外部npm封装

javascript - 如何从 UserFrosting Controller 正确返回 .xls Excel 文件并在 Angular 2+ 中处理它?

angular - 如何使用点击事件在 Angular 中切换类

json - Angular 6 : use a service to get local json data

angular - 将 ionic3 应用程序与 Firebase Analytics ionic native 插件集成

javascript - 使用 *ngIf 仅在数据加载后处理显示元素

javascript - Angular 和 Spring Boot App 上的奇怪图标

html - 如果一个 div 以 Angular 6 从该列中删除,如何将现有 div 从一列推送到另一列

angular - 使用 *ng 来渲染 Angular html 标签

javascript - CSRF错误发生在Angular2中,但在Postman中一切正常(SOAP XML Ajax)