访问使用@Input 装饰器传递的数据

Accessing the data passed using @Input decorator

我有一个看起来像这样的子组件

子组件

@Component({
   selector: 'child-component',
   //TemplateUrl, Styles and Providers
})

export Class ChildComponent implements OnInit{
  @Input()
  arrayToGet; //An array that I want to pass from Parent to child

  ngOnInit(){
     console.log('The Array I got is ', this.arrayToGet); //Undefined, Tried even with setTimeout
  }

  //A bunch of methods to work with the array I get
}

父组件

@Component({
   selector: 'parent-component',
   template: '<div>
                <child-component [arrayToGet]="models"></child-component>
              </div>',
   //A bunch of Styles and Providers
})

export class ParentComponent{
   models;

   constructor(......){}

   ngOnInit(){
      //Get an array from a service assign to this.models;
   }
}  

问题是我无法在 ChildComponent 中对 arrayToGet 执行任何操作。但是,我可以在 ChildComponent 的 HTML 中使用 arrayToGet 上的属性。

有什么想法吗?

每当尝试使用 @Input 装饰器将数据从 parent 传递到 child 并且传递数据在 child 初始化时不可用时,最好使用 setter,而不是直接绑定到 child 组件中的变量。每当父组件中的数据更新时,使用 setter 将更新子组件变量。

export Class ChildComponent implements OnInit{
  arrayToGet; //An array that I want to pass from Parent to child

  ngOnInit(){
     console.log('The Array I got is ', this.arrayToGet); //Undefined, Tried even with setTimeout
  }

  @Input('arrayToGet')
  set _arrayToGet(data: Array) {
     this.arrayToGet = data;
     console.log(this.arrayToGet);
  }

  //A bunch of methods to work with the array I get
}

试试这个:

parent.component.html

<child-component [arrayToGet]="models"></child-component>

parent.component.ts

export class ParentComponent {
  private models: Array<any> = ["hello", "world"];
}

child.component.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'child-component',
    templateUrl: './child.component.html'
})

export class ChildComponent implements OnInit {

    @Input() arrayToGet;

    ngOnInit() {
        console.log('arrayToGet', this.arrayToGet);
    }
}