typescript - 使用 ngOnInit() 而不是构造函数;@Input() 未定义
首先,如果这是糟糕的设计,我非常乐意更改。
在我的 index.html 中,我在主体里有:
<month [year]="2016" [monthOfYear]="4">Loading...</month>
month.component.ts 然后是:
import { Component, Input, OnInit } from '@angular/core';
import { DayComponent } from '../day/day.component';
import * as Models from '../../../models/_models';
@Component({
selector: 'month',
moduleId: module.id,
templateUrl: 'month.component.html',
styleUrls: ['month.component.css'],
directives: [DayComponent]
})
export class MonthComponent {
name: string;
days: Models.Day[];
@Input('year') year: number;
@Input('monthOfYear') monthOfYear: number;
month: Models.Month;
ngOnInit() {
this.month = new Models.Month(this.year, this.monthOfYear);
this.name = this.month.getMonthName();
this.days = this.month.days;
}
}
...并且 ngOnInit() 被正确调用。然而,在调用时(或者可能从未调用过,但我不知道如何确定)year 和 monthOfYear 都是 undefined。
我如何确保值在 ngOnInit() 中传入,或者是否有更好的模式来实现这一点?
答案#1
所以这其实相当简单,但从教程/文档中并不清楚。
这是解决方案:
<month year="2016" monthOfYear="4">Loading...</month>
属性周围的方括号表示组件应将其视为与父组件的数据绑定。因此,如果你想从父组件传递这些值,你可以执行以下操作:
<month [year]="year" [monthOfYear]="month">Loading...</month>
在你的情况下,你正在赋值字符串字面量,因此不需要方括号。此外,你应该声明你的组件实现了 OnInit,但这似乎对执行没有任何影响。
答案#2
如果我理解正确,你尝试将一些值从 index.html 传递到一个组件(在这种情况下它变成了根组件)。我不确定这是否可行,因为 Angular 是由根组件引导的,并且无法提供 index.html(它是承载 Angular 的页面)。
通常在 index.html 中,你会有一个根(比如说 AppComponent)。AppComponent 包含你的组件(例如 MonthComponent)。AppComponent 可以向 MonthComponent 传递值。
我希望这能帮到你
