如果 Angular 组件的引用模板没有随着状态更改而更新,则遵循以下步骤以解决此问题:
确保更改输入属性触发变化检测
在组件类中正确定义输入属性并实现 OnChanges
钩子以侦听属性更改。如果输入属性未正确实现更改检测,则模板中的绑定将不会更改。
示例:
@Input() value: any;
ngOnChanges(changes: SimpleChanges) {
if (changes.value) {
// value input has changed
}
}
手动运行变化检测
手动运行变化检测以更新组件的视图。
示例:
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `{{ value }}`
})
export class MyComponent {
value: any;
constructor(private cdr: ChangeDetectorRef) {}
updateValue(newValue: any) {
this.value = newValue;
this.cdr.detectChanges();
}
}
使用 ChangeDetectionStrategy.OnPush
如果您使用 ChangeDetectionStrategy.OnPush
更改检测策略,则必须确保您的组件状态按引用进行更改,并使用 ChangeDetectorRef.markForCheck()
手动触发变化检测。
示例:
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `{{ value }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {
value: any;
constructor(private cdr: ChangeDetectorRef) {}
updateValue(newValue: any) {
this.value = newValue;
this.cdr.markForCheck();
}
}
上一篇:Angular组件未对齐