当Angular的子组件视图没有得到更新时,可能是由于以下几个原因:
changeDetection: ChangeDetectionStrategy.Default
来使用默认的变更检测策略。@Component({
selector: 'app-child',
templateUrl: './child.component.html',
changeDetection: ChangeDetectionStrategy.Default
})
export class ChildComponent {
@Input() data: any;
}
export class ParentComponent {
parentData = { name: 'John' };
updateData() {
this.parentData.name = 'Jane';
this.cd.detectChanges(); // 手动触发变更检测
}
}
ChangeDetectorRef
的detectChanges()
或者markForCheck()
方法来触发变更检测,但是引用的是子组件的变更检测器,那么子组件的视图是不会更新的。解决方法是在父组件中引用正确的变更检测器。export class ParentComponent {
constructor(private cd: ChangeDetectorRef) {}
updateChild() {
this.cd.detectChanges(); // 引用父组件的变更检测器
}
}
通过以上方法,你应该能够解决Angular子组件视图未得到更新的问题。
上一篇:Angular子组件破坏了表格