Как передать данные из родительского компонента в дочерний компонент в Angular 4
Когда я пытаюсь передать данные от родительского к дочернему компоненту. Я получаю сообщение undefined в консоли. Данные находятся в форме массива.
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
}
Ответы
Ответ 1
Вы не можете выполнить назначение в конструкторе, так как значение еще не было заполнено, оно должно быть сделано в ngOnInit
точно так же, как проверка значения.
@Input() data;
question = [];
constructor() {
}
ngOnInit() {
this.question = this.data;
console.log(this.question);
}
Ответ 2
Это можно сделать с помощью декоратора Input()
. Смотрите ниже код -
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 {{ message }}
',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() childMessage: string;
constructor() { }
}
Больше информации