我一直试图将属性值传递到我的组件中。从我读到的一切看起来都是正确的。但它仍然不起作用。我的测试值以空值输出到屏幕和控制台。 :(
这是我的测试组件:
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”。
我可以注意到你有四件事:
- 您正在根组件中传递输入,这是行不通的。
- 正如 @alexpods 提到的,您正在使用 CamelCase。你不应该。
- 您正在传递一个表达式而不是一个字符串
[test]
。这意味着 angular2 正在寻找一个名为的变量Blue32
而不是传递原始字符串。
- You are using the constructor. That will not work, it must be after the
view has been initialized data-bound properties have been initialized (see docs for OnInit https://angular.io/docs/ts/latest/api/core/OnInit-interface.html).
因此,通过一些修复,它应该可以工作
示例已更新至 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 http://plnkr.co/edit/CO7kmS?p=preview举个例子。
Update
我看到人们仍然达到这个答案,所以我将 plnkr 更新到 beta 1,并纠正了解释中的一点:您可以在 ngAfterViewInit 中访问输入,但您可以在 ngOnInit 的生命周期的早期访问它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)