How to pass data from parent to child component in Angular 4

Viewed 61773

When I try to pass data from parent to child component. I'm getting undefined message in the console. Data is in the form of array.

parent.component.html

<div class="section welcome-section fp-section fp-table" *ngFor="let section of sections">
    <div class="fp-tableCell">
      <app-question-card [data]="section"></app-question-card>
    </div>
  </div>

child.component.ts

@Input() data;
  question = [];
  constructor() {
    this.question = this.data;
  }

  ngOnInit() {
    console.log(this.question); //returns undefined
  }
4 Answers

It can be done using Input()decorator. See below code -

parent.component.ts -

import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child [childMessage]="parentMessage"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent{
  parentMessage = "message from parent"
  constructor() { }
}

child.component.ts -

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
      Say {{ childMessage}}
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childMessage: string;

  constructor() { }

}

More Information

According to angular Lifecycle use the ngOnInit for initializing input values

@Input() data;


constructor() {
}

ngOnInit() {
  let question = this.data;
  console.log(this.question);
}

With the help of Input() we can pass data

Child.html

<app-chart [userDetails]='<< JSON OBJ | ANY VALUE WHICH YOU WANT TO PASS >>'></app-chart>

chart.component.ts

@Input() userDetails: any = [];

ngOnInit() {
    console.log(this.userDetails); // as per angular Lifecycle use the ngOnInit for initializing input values
}
Related