我像这样将一个数组传递到我的组件中;
<app-bar-chart-demo [chartLabelObject]="['2006', '2007', '2008', '2009', '2010', '2011', '2012']"></app-bar-chart-demo>
我正在像这样在组件中检索该数组
@Component({
...
inputs:['chartLabelObject']
})
然后我像这样将一个变量设置为它的值
export class BarChartDemoComponent {
...
barChartLabels:string[] = this.chartLabelObject;
...//and doing stuff with it
}
然而,在我使用它时它似乎是“未定义”的。如果我记录它的值以响应按下按钮,我看到它已设置,如果我将它放入“导出类”的开头或下面的“构造函数”中未设置!
我应该在哪里设置'barChartLabels:string[]'?
最佳答案
对输入属性的每次更改都会触发对组件上的 ngOnChanges
的调用。这是您应该设置 barChartLabels
属性的地方。
@Component({
...
inputs:['chartLabelObject']
})
export class BarChartDemoComponent implements OnChanges {
barChartLabels:string[];
constructor() { }
ngOnChanges(changes){
if(changes["chartLabelObject"]){
this.barChartLabels = this.chartLabelObject;
}
}
}
您还可以稍微清理一下您的逻辑,使用 @Input
装饰器将输入映射直接映射到您的输入,如下所示:
@Component({
...
})
export class BarChartDemoComponent {
@Input('chartLabelObject') barChartLabels:string[];
constructor() { }
}
关于javascript - angular2 组件生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42010990/