Accessing the data passed using @Input decorator

寵の児 提交于 2019-12-08 03:12:06

问题


I have a child component that looks like this

Child Component

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

Parent Component

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

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.

Any thoughts?


回答1:


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
}



回答2:


Try this :

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


来源:https://stackoverflow.com/questions/46138267/accessing-the-data-passed-using-input-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!