我在离子组件中有一个按钮,只想在播放音频时显示。
<button *ngIf="playing">Stop Audio</button>
我有一个服务,它公开一个公共属性,当播放音频时为true,否则为false。
public playing = new BehaviorSubject<boolean>(false)
当我播放音频时,该按钮会正确显示,但是当音频停止播放时,除非我单击其他按钮来更改视图状态,否则该按钮将保留。
我知道BehaviorSubject正常工作,因为当我订阅它并在控制台上记录输出时,当音频正在播放(并且视图更新)时,它将记录true
,而在音频停止时(视图不会记录false
)没有更新)。
您需要使用异步管道:*ngif="audioPlayingService.playing | async"
因此,可以通过两种方法在组件中完成此操作。一种是在组件上添加属性,然后将值提取到其中。所以你要做这样的事情:
组件类
export class MyComponent implements OnInit {
playing: boolean = false;
constructor(private audioService: AudioService) {}
ngOnInit(): void {
this.audioService.playing.subscribe(playing => this.playing = playing);
}
}
组件模板
<button *ngIf="playing">Stop Audio</button>
另一种解决方案是使用异步管道,如建议的Ploppy。然后,您可以执行以下操作:
组件类
export class MyComponent implements OnInit {
playing: Observable<boolean>;
constructor(private audioService: AudioService) {}
ngOnInit(): void {
this.playing = this.audioService.playing;
}
}
[组件模板
<button *ngIf="(playing | async)">Stop Audio</button>