Angular 2组件@Input无法正常工作

Zorthgo:

我一直试图将属性值传递到组件中。从我阅读的内容来看,一切看起来都是正确的。但是它仍然无法正常工作。我的测试值作为空值输出到屏幕和控制台。:(

这是我的测试组件:

import {Component, Input} from 'angular2/angular2';

@Component({
    selector: 'TestCmp',
    template: `Test Value : {{test}}`
})

export class TestCmp {

    @Input() test: string;

    constructor()
    {
        console.log('This if the value for user-id: ' + this.test);
    }
}

这就是我从父页面调用组件的方式。

<TestCmp [test]='Blue32'></TestCmp>

当页面呈现的测试值为空时。我只看到“测试值:”。

代替“测试值:Blue32”。

埃里克·马丁内斯(Eric Martinez):

您需要注意四件事:

  • 您正在根组件中传递输入,该输入将不起作用。
  • 如@alexpods所述,您正在使用CamelCase。你不应该。
  • 您正在通过传递表达式而不是字符串[test]这意味着angular2正在寻找名为的变量,Blue32而不是传递原始字符串。
  • 您正在使用构造函数。这将不起作用,必须在初始化视图之后初始化数据绑定属性(请参阅docs的OnInit)。

因此,经过一些修复,它应该可以工作

示例已更新为Beta 1

import {Component, Input} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

@Component({
  selector : 'childcmp',
  template: `Test Value : {{test}}`
})
class ChildCmp {
    @Input() test: string;
    ngOnInit() {
        console.log('This if the value for user-id: ' + this.test);
    }
}

@Component({
    selector: 'testcmp',
    template : `<childcmp [test]="'Blue32'"></childcmp>`
    directives : [ChildCmp]
})
export class TestCmp {}

bootstrap(TestCmp);

请以这个plnkr为例。

更新资料

我看到人们仍然可以找到答案,因此我将plnkr更新为beta 1,并更正了以下解释:可以在ngAfterViewInit中访问输入,但是可以在ngOnInit的生命周期中更早地访问它们。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章