数据更改时重新创建组件

Recreating a component when data changes

好的,这个问题似乎有很多答案,但我一直无法理解我应该做什么。

我目前有一个 child 组件,当有人单击另一个 child 组件的播放按钮时,该组件就会被创建。这是通过与我的 parent 共享数据的服务发生的,然后 parent 传递数据并创建我的 child audio-player 组件。我遇到的问题是,如果用户导航到另一个页面并单击以播放该页面上的音频,旧音频仍然存在并且新音频不会启动。

是否有生命周期挂钩或方法可以用来销毁我的旧音频组件并创建新的音频 onclick?

信息框 - 单击播放按钮时初始激活发生的地方。

export class InfoBoxComponent implements OnInit {
  ...

  activateAudioPlayer(session) {
    this.newAudioService.newAudio(session)
  }
}

新音频服务

export class NewAudioService {
  newActiveAudioSource: Subject<string> = new Subject<string>();

  newAudio(session) {
    this.newActiveAudioSource.next(session);
  }

  newActiveAudio$ = this.newActiveAudioSource.asObservable();
}

前端组件 - Parent 信息框和音频播放器组件

@Component({ 
   template: `<audio-player *ngIf='newActiveAudio' [newActiveAudio]='newActiveAudio'></audio-player>`,
})

export class FrontendComponent implements OnInit {

  ...

  ngOnInit() {
    this.sub = this.newAudioService.newActiveAudio$.subscribe(
      newActiveAudio => {
        this.newActiveAudio = newActiveAudio;
      });
  }

  ngOnDestroy() {
    // prevent memory leak when component destroyed
    this.sub.unsubscribe();
  }
}

一种可能的方法是设置 this.newActiveAudio = false,然后让 Angular 使用 setTimeout() 更新视图,然后为 newActiveAudio 设置新值:

this.sub = this.newAudioService.newActiveAudio$.subscribe(newActiveAudio => {
    this.newActiveAudio = false;
    setTimeout(() => {
        this.newActiveAudio = newActiveAudio;
    });
});

为此找到了一些技巧。将您的元素放在一个元素数组中并使用 trackBy

创建 ngFor
 <component *ngFor="let o of [object]; trackBy: trackByObjectProperty">
        </component>

这是一个在 key 值更改时重新创建视图的小指令:

import {
  Directive,
  EmbeddedViewRef,
  Input,
  OnChanges,
  SimpleChanges,
  TemplateRef,
  ViewContainerRef
} from '@angular/core';

@Directive({
  selector: '[wRecreateViewKey]'
})
export class RecreateViewDirective implements OnChanges {
  @Input('wRecreateViewKey') key: any;

  viewRef: EmbeddedViewRef<any>;

  constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.key) {
      if (this.viewRef) {
        this.destroyView();
      }

      this.createView();
    }
  }

  private createView() {
    this.viewRef = this.viewContainer.createEmbeddedView(this.templateRef);
  }

  private destroyView() {
    this.viewRef.destroy();
    this.viewRef = null;
  }
}

用法示例:

<!-- `some-component` will be destroyed and recreated every time `value` changes. -->

<some-component *wRecreateViewKey="value"></some-component>

<!-- Can also be used on regular DOM elements or container -->
<div *wRecreateViewKey="value"></div>
<ng-container *wRecreateViewKey="value"></ng-container>

将 newAudioService 设置为 null 后,应使用 ChangeDetectorRef.detectChanges() 强制屏幕更新。 这会破坏组件。 然后我们重新配置 newActiveAudio 并重新生成组件。

html

<audio-player *ngIf='newActiveAudio' [newActiveAudio]='newActiveAudio'></audio-player>

TS

constructor(private changeDetectorRef: ChangeDetectorRef) {
}
    
ngOnInit() {
    this.sub = this.newAudioService.newActiveAudio$.subscribe(
        newActiveAudio => {
            this.newActiveAudio = null;
            this.changeDetectorRef.detectChanges();
            this.newActiveAudio = newActiveAudio;
        }
    );
}