当使用Angular OnPush策略时,组件中的输入属性(@Input)如果未通过引用变化,则不会自动更新模板。而是需要手动通知变化检测器(ChangeDetectorRef)进行检测。
例如:
@Component({
selector: 'app-my-component',
template: {{ myInput }}
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
@Input() myInput: string;
constructor(private cdr: ChangeDetectorRef) {}
updateInput(newValue: string) { this.myInput = newValue; this.cdr.detectChanges(); // 手动检测变化以触发模板更新 } }
在上面的示例中,通过调用ChangeDetectorRef的detectChanges()方法,通知变化检测器手动检测输入属性的变化并更新模板。