Angular 4 @Input() 值在 ngOnInit() 中未定义

wgf*_*242 3 angular

月-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));
  }
}
Run Code Online (Sandbox Code Playgroud)

月-日.component.html

<p>month-date works! {{month?.id}}</p>
Run Code Online (Sandbox Code Playgroud)

月-日.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);
  }}
Run Code Online (Sandbox Code Playgroud)

month?.id 在 中正确显示month-detail.component.html,但app-month-date在 中带有标记的月份未定义month-date.component.ts。也许没有得到 ngOnInit 的值?

Plo*_*log 5

您可以通过在父模板中包含 *ngIf 来确保在将月份输入值发送给它之前未初始化子组件来解决此问题:

@Component({
  template: `{{month?.id}} <app-month-date *ngIf="month" [month]="month"></app-month-date>`
})
Run Code Online (Sandbox Code Playgroud)