可以在 @Input 的 setter 中手动触发变化检测,从而更新 UI。代码示例如下:
import { Component, Input, OnInit, OnChanges, SimpleChanges, NgZone } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit, OnChanges {
@Input() text: string;
constructor(private ngZone: NgZone) { }
ngOnInit(): void {
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.text) {
this.ngZone.run(() => { // 手动触发变化检测
// 代码逻辑
});
}
}
}
在上面的例子中,我们使用了 NgZone,通过其 run 方法手动触发了变化检测。这样,在父组件中修改了 @Input 值后,就能够及时更新子组件的 UI。