[英]angular2 component lifecycle
I am passing an array into my component like so; 我将数组传递到组件中,就像这样;
<app-bar-chart-demo [chartLabelObject]="['2006', '2007', '2008', '2009', '2010', '2011', '2012']"></app-bar-chart-demo>
I am retrieving that array in the component like so 我正在像这样检索组件中的数组
@Component({
...
inputs:['chartLabelObject']
})
I am then setting a variable to its value like so 然后我将变量设置为其值,如下所示
export class BarChartDemoComponent {
...
barChartLabels:string[] = this.chartLabelObject;
...//and doing stuff with it
}
However it appears that it is 'undefined' at the point i use it.If i log its value in response to a button being pressed i see it is set, if i put it into the start of the 'export class' or below in the 'constructor' it is not set! 但是似乎在我使用它的时候它是``未定义的''。如果我记录它的值以响应按下按钮,我会看到它已经设置好了,如果我将其放在``导出类''的开头或下方没有设置“构造函数”!
Where should i set the 'barChartLabels:string[]'? 我应该在哪里设置“ barChartLabels:string []”?
Every change to an input property triggers a call to ngOnChanges
on the component. 对输入属性的每次更改都会触发对组件上的
ngOnChanges
的调用。 This is where you should set your barChartLabels
property. 在此处应设置
barChartLabels
属性。
@Component({
...
inputs:['chartLabelObject']
})
export class BarChartDemoComponent implements OnChanges {
barChartLabels:string[];
constructor() { }
ngOnChanges(changes){
if(changes["chartLabelObject"]){
this.barChartLabels = this.chartLabelObject;
}
}
}
You could also clean up your logic a bit and just have the input map directly to your input by using the @Input
decorator like so: 您还可以稍微整理一下逻辑,只需使用
@Input
装饰器将输入映射直接映射到您的输入即可,如下所示:
@Component({
...
})
export class BarChartDemoComponent {
@Input('chartLabelObject') barChartLabels:string[];
constructor() { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.