本文介绍了访问使用@Input装饰器传递的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a child component that looks like this

子组件

@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 上的属性.

The problem is that I can't perform any operations on arrayToGet inside my ChildComponent. However I am able to use the properties on arrayToGet inside my ChildComponent's HTML.

有什么想法吗?

推荐答案

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

Whenever trying to pass data from parent to child using @Input decorator and passing data is not available at the time of child initialzation, better to use setter, instead of just binding directly in to variable in child component. Using setter will updates the child component vairable, whenever the data is updated in parent component.

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
}

这篇关于访问使用@Input装饰器传递的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:00