Angular Directive 不会从 ngOnDestroy 方法中所做的组件接收更改

问题描述

组件销毁后出现了意外的指令行为。

指令未在组件中的 ngOnDestroy 方法中进行更改

组件:

export class InfoButtonComponent implements OnDestroy {
    display = false;

    justMethod() {
      this.display = true | false; // (whatever) works fine,directive recevied that display was changed
    }

    ngOnDestroy(): void {
      this.display = false; // directive doesn't handle it
      this.cdr.detectChanges();
    }
}

<div
    [show]="display"
  >1</div>

指令:

export class TooltipDirective implements OnChanges {
  @input() show = false;
  ngOnChanges(changes: SimpleChanges): void {
    // get changes from component made in other methods
    // doesn't get changes made in ngOnDestroy method
  }
}

解决方法

似乎与文档对 ngOnDestroy() 的描述相符:

在 Angular 销毁指令或组件之前立即调用。

我会强调“立即”,并不会期望在之后运行另一轮更改检测。

目前尚不清楚您尝试完成的任务,但这听起来像是黑客攻击。