繁体   English   中英

angular2组件生命周期

[英]angular2 component lifecycle

我将数组传递到组件中,就像这样;

 <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() { }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM