Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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   } 
like image 856
Rahul Dagli Avatar asked Jul 19 '17 11:07

Rahul Dagli


People also ask

How do you pass data from parent component to child component in Angular?

To let Angular know that a property in a child component or directive can receive its value from its parent component we must use the @Input() decorator in the said child. The @Input() decorator allows data to be input into the child component from a parent component.

Can we pass data from child to parent in Angular?

The Angular documentation says "The @Output() decorator in a child component or directive lets data flow from the child to the parent." This is exactly what we want.


2 Answers

You can't do the assignment in the constructor as the value has not yet been populated, it should be done in ngOnInit just like your check of the value.

@Input() data; question = [];  constructor() { }  ngOnInit() {   this.question = this.data;   console.log(this.question); } 
like image 57
Igor Avatar answered Sep 23 '22 03:09

Igor


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

like image 32
ShaileshDev Avatar answered Sep 23 '22 03:09

ShaileshDev