简体   繁体   English

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

[英]Angular 4 @Input() value is undefined in ngOnInit()

month-detail.component.html 一个月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 一个月date.component.html

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

month-date.component.ts 一个月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 . month?.id在month-detail.component.html中正确显示,但在month-detail.component.html中未使用标记app-month-date定义month-date.component.ts Maybe not get the value on ngOnInit? 也许无法获得ngOnInit的值?

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: 您可以通过在父模板中添加* ngIf来确保在将月份输入值发送给子组件之前未初始化子组件来解决此问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM