使用 markForCheck() 方法代替 detectChanges() 方法。这种情况通常发生在组件使用了 OnPush 变更检测策略时。
示例代码:
@Component({ selector: 'app-example', templateUrl: './example.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class ExampleComponent implements OnInit, DoCheck {
@Input() data: any;
constructor(private cdr: ChangeDetectorRef) { }
ngOnInit() { }
ngDoCheck() { console.log('ngDoCheck() called'); // 这条语句永远不会被执行 }
updateData() { // this.cdr.detectChanges(); // 不会触发 ngDoCheck() this.cdr.markForCheck(); // 会触发 ngDoCheck() }
}
在上面的代码中,使用了 OnPush 变更检测策略,同时实现了 DoCheck 接口。当调用 updateData() 方法时,使用了 markForCheck() 方法来通知 Angular 组件需要检测更新,这会触发 ngDoCheck() 方法的执行。相反,如果使用 detectChanges() 方法,ngDoCheck() 不会被调用。