How to pass data from parent to child component in Angular 4
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