可以在组件中使用ChangeDetectorRef来避免每次点击事件都会触发父组件的重新渲染。具体的实现方法是在组件的构造函数中实例化ChangeDetector对象,然后在点击事件回调函数中调用markForCheck方法来标记组件已经发生了变化,但并不立即重新进行检测和渲染,直到Angular的变更检测机制认为有必要时再更新视图。
示例代码:
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-child',
template: {{ count }}
})
export class ChildComponent {
count = 0;
constructor(private cdr: ChangeDetectorRef) {}
onClick() { this.count++; this.cdr.markForCheck(); } }