【发布时间】:2021-09-19 04:25:33
【问题描述】:
我使用的是 Angular 9+,我对 ngOnChanges 生命周期的行为有点困惑。
我要做什么
我有一个异步操作,它使用 @Input() 装饰器为子组件设置一个值(对象类型)。代码如下。 (StackblitzHere)
parent.ts
import { AfterViewInit, Component, VERSION, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
@ViewChild(ChildComponent) childComponent: ChildComponent;
data = { value: null };
constructor() {}
ngAfterViewInit() {
const foo = of([1])
.pipe(delay(500))
.subscribe(subscriber => {
this.data = { value: 123 };
this.childComponent.printState();
});
}
}
Parent.Html
<app-child [data]="data"></app-child>
子组件
import { Component, Input, OnChanges } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnChanges {
@Input() data = null;
constructor() {}
ngOnChanges(changes) {
console.log('ngOnChanges');
}
printState() {
console.log('printState');
console.log(this.data.value);
}
}
我想要的是,一旦我更改了值,我就会尝试使用上面显示的视图子引用来打印设置值的值。
理想的顺序应该是
ngOnChanges // initial value
ngOnChanges // after value set
printState // after calling printState()
但我明白
ngOnChanges
printState
ngOnChanges
在相当混乱的控制台中。为什么 ngOnChanges 也没有立即被解雇。为什么要花时间。谁能解释一下。
谢谢,注意安全:)
【问题讨论】:
标签: angular angular9 angular10