2017-02-02 113 views
0

我將數組傳遞到我的組件中,像這樣;angular2組件生命週期

<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 []'?

回答

0

每次對輸入屬性的更改都會觸發組件上的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() { } 
}