Parent component passes value to child component


#1
<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <child [msg]="msg"></child>
</ion-content>
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  msg: string = "This is the msg of the parent component";
  constructor(public navCtrl: NavController) {

  }

}
import { Component, Input } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: 'child.html'
})
export class ChildComponent {

  @Input() msg: string;

  constructor() {
    console.log(this.msg); //Why is the output undefined here?
  }

}


#2

@rex19001 You are logging in the constructor. When the component is being created its input properties are still empty.

The value is shown in the html? If you want to log in your ts file, you could create a method ngOnChanges and log there:

constructor() {}

ngOnChanges () {
    console.log('msg', this.msg);
}