[英]Angular 4 @Input() value is undefined in ngOnInit()
一個月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));
}
}
一個月date.component.html
<p>month-date works! {{month?.id}}</p>
一個月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-detail.component.html
中未使用標記app-month-date
定義month-date.component.ts
。 也許無法獲得ngOnInit的值?
您可以通過在父模板中添加* ngIf來確保在將月份輸入值發送給子組件之前未初始化子組件來解決此問題:
@Component({
template: `{{month?.id}} <app-month-date *ngIf="month" [month]="month"></app-month-date>`
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.