4

month-detail.component.html

import ...
@Component({
  template: `{{month?.id}} <app-month-date [month]="month"></app-month-date>`
})
export class MonthDetailComponent implements OnInit {
  month: Month;
  ngOnInit(): void {
    this.route.params
      .switchMap((params: Params) => this.monthService.getMonth(+params["id"]))
      .subscribe(month => (this.month = month));
  }
}

month-date.component.html

<p>month-date works! {{month?.id}}</p>

month-date.component.ts

import { Component, OnInit, Input } from "@angular/core";
import { Month } from "app/attendance/month";

@Component({
  selector: "app-month-date",
  ...
})
export class MonthDateComponent implements OnInit {
  @Input() month: Month;
  ngOnInit() {
    //undefined --- here
    console.log(this.month);
  }}

month?.id shows correctly in month-detail.component.html, but month is undefined with tag app-month-date in month-date.component.ts. Maybe not get the value on ngOnInit?

2
  • 1
    Yup it's undefined cause the ngOnInit will tigger before the month is set. In this case you want tot use ngOnChanges Commented Nov 28, 2017 at 14:44
  • 2
    If you really think about why you have month?.id instead of month.id, the answer will become apparent. Commented Nov 28, 2017 at 14:45

1 Answer 1

6

You can resolve this by ensuring the child component is not initialised before the month input value is sent to it by including an *ngIf in your parent template:

@Component({
  template: `{{month?.id}} <app-month-date *ngIf="month" [month]="month"></app-month-date>`
})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.