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 }
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.
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.
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); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With