adityav
adityav

Reputation: 201

Accessing the data passed using @Input decorator

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?

Upvotes: 2

Views: 2734

Answers (2)

Chandru
Chandru

Reputation: 11192

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

Upvotes: 0

Rajez
Rajez

Reputation: 4077

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
}

Upvotes: 5

Related Questions