【发布时间】:2020-09-03 11:18:56
【问题描述】:
我有一组不同的子视图,需要在某个条件下加载。
一切正常,但是,我收到一条消息,ViewDestroyedError: Attempt to use a destroyed view: detectChanges。所以我相信这会导致在父负载上,所有视图都渲染一次。但是,只要视图满足条件,它就有可能在尝试使用被破坏的视图之前已经渲染。
示例代码
<div class="parent>
<app-dropdown *ngSwitchCase="'dropdown'" [reply]="answer" (response)="myResponse($event)"></app-dropdown>
<app-select *ngSwitchCase="'select'" [reply]="answer" (response)="myResponse($event)"></app-select>
<app-input *ngSwitchCase="'input'" [reply]="answer" (response)="myResponse($event)"></app-input>
</div>
在上面的代码中,我通常会按顺序从 API 中获得类型“选择”、“下拉”和“输入”的回复。或者它可能会动态改变顺序。但是在这里我收到了 ViewDestroyedError 的错误:尝试使用已破坏的视图:detectChanges。
我尝试添加 ChangeDetectorRef,但它对我来说是新的,所以无法找到方法。 我的一个孩子的代码如下。
export class DropdownComponent implements OnInit {
@Input() reply: any;
@Output() response = new EventEmitter();
constructor(private cdRef: ChangeDetectorRef) {
}
ngOnInit() {
if (this.reply.answerType === 'speciality') {
this.response.emit('Hello');
}
}
ngOnDestroy(): void {
}
}
我只是检查回复,如果符合条件,则发出回复。但是由于视图已经与其他组件一起呈现,因此得到空白响应。我也尝试更改 ngOnChange() 而不是 ngOnInit 但仍然是同样的问题。
【问题讨论】:
-
很难猜出你的实际代码发生了什么。上面的示例没有说明任何内容。请分享父组件、所有子组件和完整堆栈跟踪的完整代码。此类错误通常是由于组件销毁后完成某些异步操作而发生的。因此,请提供更多代码?
标签: angular components parent-child angular-changedetection