wgf4242
wgf4242

Reputation: 831

Angular 4 @Input() value is undefined in ngOnInit()

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?

Upvotes: 4

Views: 5468

Answers (1)

Plog
Plog

Reputation: 9622

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>`
})

Upvotes: 6

Related Questions