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

标签 angular

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 在 month-detail.component.html 中正确显示,但在 month-date 中使用标记 app-month-date 未定义月份.component.ts。 可能无法获取 ngOnInit 的值?

最佳答案

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

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

关于Angular 4 @Input() 值在 ngOnInit() 中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47534248/

相关文章:

angular - 对于 Angular 应用程序,我应该在哪里存储从身份验证服务器生成的 JWT token ?

javascript - 文本不仅使背景层具有动画效果

javascript - 预检响应中的 Access-Control-Allow-Headers 不允许请求 header 字段 Time-Zone

angular - 同一域中的多个 PWA

javascript - Angular 12+ : Is there a Simple way to apply display mask/pipe for Reactive Form?

node.js - 在公共(public) Node 服务器上运行多个 Angular 应用程序

javascript - 如何将数据从 Angular 2 中的多个组件传递到单个 @Input?

javascript - 如何解决 typescript 中的多个 promise

angular - 在使用可观察对象通过 NGRX 调用 API 之前检查 Angular Store 中的数据

javascript - Angular 2 : AuthGard renders the page before it checks whether SecurityContext is applied or not