如何初始化@Input?
How to initialize @Input?
我试着这样做:
@Input() data: any[] = [];
在 ngOnInit 中我看到 undefined
:
ngOnInit() {
console.log(this.data);
}
因此,在下面的代码中,当我尝试获取长度时出现错误:return this.data.length;
因为未定义。
为什么默认情况下初始化不起作用?
@Input() data: any[] = [];
您需要使用 OnChanges
angular 指令。
export class AppComponent implements OnChanges {
...
ngOnChanges(changes: SimpleChanges) {
this.data = changes.data.currentValue; // fetch the current value
console.log(this.data);
}
...
}
有关此指令的更多信息,请参见 docs。
Respond when Angular (re)sets data-bound input properties. The method
receives a SimpleChanges object of current and previous property
values.
Called before ngOnInit() and whenever one or more data-bound input
properties change.
要接收更改,请执行以下操作:
ngOnChanges(changes: SimpleChanges) {
if (changes.data.currentValue) {
// Do Something with that data
}
}
我试着这样做:
@Input() data: any[] = [];
在 ngOnInit 中我看到 undefined
:
ngOnInit() {
console.log(this.data);
}
因此,在下面的代码中,当我尝试获取长度时出现错误:return this.data.length;
因为未定义。
为什么默认情况下初始化不起作用?
@Input() data: any[] = [];
您需要使用 OnChanges
angular 指令。
export class AppComponent implements OnChanges {
...
ngOnChanges(changes: SimpleChanges) {
this.data = changes.data.currentValue; // fetch the current value
console.log(this.data);
}
...
}
有关此指令的更多信息,请参见 docs。
Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.
Called before ngOnInit() and whenever one or more data-bound input properties change.
要接收更改,请执行以下操作:
ngOnChanges(changes: SimpleChanges) {
if (changes.data.currentValue) {
// Do Something with that data
}
}