我正在学习angular2和ang-book2建议将变量传递给子组件我应该:
在父视图中(在parent app.ts中定义的random_number):
<app-child
[passedToChild] = "random_number"
></app-child>
在子组件中:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
inputs: ['passedToChild']
})
export class ChildComponent implements OnInit {
passedToChild :number;
constructor() { console.log(this.passedToChild)}
ngOnInit() {
}
}
这导致控制台中的输出未定义 .
另一方面,这里https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child他们使用@Input将var传递给子元素 .
第二种选择似乎对我有用,但我想了解原因 . 上面的书和上面的页面都没有解释第一种方法导致未定义的差异或原因 .
2 回答
在
@Component()
配置对象上使用inputs
数组应该与将@Input()
装饰器添加到属性AFAIK相同,这不是您的代码不起作用的原因 .相反,您的问题是您在构造函数中检查属性是否过早设置 .
相反,检查
ngOnInit()
方法内部,应该已经为您设置了属性 .来自the docs:
如果要如您所示绑定子属性,则必须使用
@Input()
decorator注释子属性 . 如果子属性没有用@Input()
装饰器修饰,那么它必须是书中的错误 .