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
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
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
}
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);
}
According to angular Lifecycle use the ngOnInit for initializing input values
@Input() data;
constructor() {
}
ngOnInit() {
let question = this.data;
console.log(this.question);
}