好的,所以这个问题似乎有很多答案,但我还没能理解我应该做些什么。
当前有人点击其他子组件的播放按钮时,我正在创建一个子组件。这是通过与父母共享数据的服务发生的,然后父母传递数据并创建我的子音频播放器组件。我遇到的问题是,如果用户导航到另一个页面并点击播放该页面上的音频,则旧音频仍然存在并且新音频不会启动。
是否有生命周期挂钩或方法可用于销毁我的旧音频组件并创建新的音频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();
}
前端组件 - 信箱和音频播放器的父组件
@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();
}
}
答案 0 :(得分:4)
为此找到了一个小技巧。将您的元素放在一个元素数组中,并使用trackBy
创建ngFor <component *ngFor="let o of [object]; trackBy: trackByObjectProperty">
</component>
答案 1 :(得分:3)
这是一个小的伪指令,当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>
答案 2 :(得分:2)
可能的方法是设置this.newActiveAudio = false
,然后让Angular使用setTimeout()
更新视图,然后为newActiveAudio
设置新值:
this.sub = this.newAudioService.newActiveAudio$.subscribe(newActiveAudio => {
this.newActiveAudio = false;
setTimeout(() => {
this.newActiveAudio = newActiveAudio;
});
});