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

When I try to pass data from parent to child component. I get an undefined message in the console. The data is in the form of an 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
  }
+19
source share
2 answers

You cannot perform an assignment in the constructor, since the value has not yet been filled, it must be done in ngOnInitexactly the same way as checking the value.

@Input() data;
question = [];

constructor() {
}

ngOnInit() {
  this.question = this.data;
  console.log(this.question);
}
+30
source

This can be done using a decorator Input(). 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 {{ message }}
  ',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childMessage: string;

  constructor() { }

}

More info

0

All Articles