【问题标题】:Angular 2 - Component Input IssueAngular 2 - 组件输入问题
【发布时间】:2015-11-25 15:07:09
【问题描述】:

我无法让 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 人,但行为相同。

我正在使用带有 traceur 的 ES6。我已经查看了这个问题,但无法解决我的问题:Angular 2 Component @Input not working

【问题讨论】:

  • afterViewInit里面打印出来,在施工的时候是不行的。

标签: angular


【解决方案1】:

我知道这个问题已经有 9 个月了,你可能仍然设法自己解决了:

问题是您试图在构造函数中获取组件的值,该构造函数在该组件被实例化但绑定尚未初始化时被调用。你需要实现AfterViewInit接口而不是构造函数:

@Component(...)
export class PeopleSearchList implements AfterViewInit {
    constructor() {
    }

    ngAfterViewInit() {
        console.log('People-Search-List:' + this.people);
    }
}

【讨论】:

    【解决方案2】:

    试试类似的东西,它对我有用:

    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);
        }
    }
    

    【讨论】:

      【解决方案3】:

      使用ngOnChanges() 检测数据何时进入您的输入。 在输入可用之前调用构造函数。

      ngOnChanges(): void {
          console.log('People-Search-List:' + this.people);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-02-20
        • 2017-04-11
        • 2020-05-19
        • 1970-01-01
        • 2016-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-04
        相关资源
        最近更新 更多