按钮显示或隐藏内容 - angular BehaviorSubject

button show or hide content - angular BehaviourSubject

我有一个按钮,每次点击都会显示或隐藏内容

HTML:

<button (click)="showHide()">
    {{ content$ ? 'Hide'  : 'show'  }}
</button>
<div *ngIf="content$" >
    CONTENT
</div>

TS:

readonly content$ = new BehaviorSubject<boolean>(false);
showHide(): void {
    this.content$.next(true);
}

这段代码没有给出任何错误,但它总是显示内容,我无法隐藏它,有什么帮助吗?

您需要使用异步管道来读取可观察值。

<div *ngIf="content$ | async" >
 CONTENT
</div>

https://angular.io/api/common/AsyncPipe

您好,欢迎来到 Whosebug!

您已正确地为 BehaviorSubject 设置了一个新值,并且:*ngIf="content$"您只是在检查 BehaviorSubject 是否存在。

为了获得您必须的内容:

<div *ngIf="content$ | async; let content">
  CONTENT
</div>

使用 let content,您可以访问主题的值,以备不时之需;)

您可以在 AsyncPipe doc

上获得更多信息