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 中使用标记
。
可能无法获取 ngOnInit 的值?app-month-date
未定义月份.component.ts
最佳答案
您可以通过在父模板中包含 *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/