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

adi*_*yav 2 angular2-components angular

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

子组件

@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
}
Run Code Online (Sandbox Code Playgroud)

父组件

@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;
   }
}  
Run Code Online (Sandbox Code Playgroud)

问题是我无法在arrayToGet我的ChildComponent. 不过,我可以使用我的 HTMLarrayToGet内部的属性。ChildComponent

有什么想法吗?

Raj*_*jez 5

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

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
}
Run Code Online (Sandbox Code Playgroud)