如何从 Angular 组件中销毁 VexFlow 渲染器?

How to destroy a VexFlow renderer from an Angular component?

在 Angular 应用程序中,我正在创建 VexFlow 渲染器:

ngAfterViewInit() {
  this.createSheet();
}
private createSheet() {
  if (this.soundtrack != null) {
    if (this.soundtrack.hasNotes()) {
      this.sheetService.createSoundtrackSheet(this.name, this.soundtrack);
    }
  }
}

使用服务方式:

private VF = vexflow.Flow;
private renderContext(name: string, width: number, height: number) {
  const elementName = ELEMENT_PREFIX + name;
  const element = document.getElementById(elementName);
  const renderer = new this.VF.Renderer(element, this.VF.Renderer.Backends.SVG);
  renderer.resize(width, height);
  return renderer.getContext();
}

我正在将 DOM 引用 document.getElementById(elementName); 传递给渲染器构造函数。

我应该在 ngOnDestroy() 组件方法中做一些释放吗?

更新:实际的完整组件是这样的:

export class SheetComponent implements OnInit, AfterViewInit {

  @Input() soundtrack: Soundtrack;
  @Input() device: Device;
  name: string;

  constructor(
    private sheetService: SheetService
  ) { }

  ngOnInit() {
    this.initializeName();
  }

  ngAfterViewInit() {
    this.createSheet();
  }

  private initializeName() {
    if (this.soundtrack != null) {
      this.name = NAME_PREFIX_SOUNDTRACK + this.soundtrack.name;
    } else if (this.device != null) {
      this.name = NAME_PREFIX_DEVICE + this.device.name;
    }
  }

  private createSheet() {
    if (this.soundtrack != null) {
      if (this.soundtrack.hasNotes()) {
        this.sheetService.createSoundtrackSheet(this.name, this.soundtrack);
      }
    } else if (this.device != null) {
      this.sheetService.createDeviceSheet(this.name, this.device);
    }
  }

}

使用模板:

<div id="{{name}}"></div>

现在,也许有一种方法可以使用 @ViewChild(name) name: ElementRef; 注释,但这无法编译:

export class SheetComponent implements OnInit, AfterViewInit {

  @Input() soundtrack: Soundtrack;
  @Input() device: Device;
  name: string;
  @ViewChild(name) sheetElement: ElementRef;

  constructor(
    private sheetService: SheetService
  ) { }

  ngOnInit() {
    this.initializeName();
  }

  ngAfterViewInit() {
    this.createSheet();
  }

  private initializeName() {
    if (this.soundtrack != null) {
      this.name = NAME_PREFIX_SOUNDTRACK + this.soundtrack.name;
    } else if (this.device != null) {
      this.name = NAME_PREFIX_DEVICE + this.device.name;
    }
  }

  private createSheet() {
    if (this.soundtrack != null) {
      if (this.soundtrack.hasNotes()) {
        this.sheetService.createSoundtrackSheet(this.sheetElement.nativeElement.id, this.soundtrack);
        // this.soundtrackStore.setSoundtrackSheet(this.name, sheet); TODO
      }
    } else if (this.device != null) {
      this.sheetService.createDeviceSheet(this.sheetElement.nativeElement.id, this.device);
      // this.deviceStore.setDeviceSheet(this.name, sheet); TODO
    }
  }

}

没有。您无需执行任何操作即可从视图中删除 DOM 个元素。

当组件被销毁时,父 DOM 元素的所有子元素也被销毁。包括附加到此元素的 DOM 个事件侦听器。

您应该使用@ViewChild 之类的视图查询来访问DOM 元素并将其传递给函数。而不是直接查询文档。