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

时间:2017-09-10 07:21:14

标签: angular angular2-components

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

子组件

@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;
   }
}  

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

有什么想法?

2 个答案:

答案 0 :(得分:1)

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

setter

答案 1 :(得分:0)

试试这个:

<强> 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);
    }
}