Home > OS >  button show or hide content - angular BehaviourSubject
button show or hide content - angular BehaviourSubject

Time:11-27

I have a button, that on every click should display or hide content

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);
}

and this code does not gives any error, but it always displays content and i cannot hide it, any help?

CodePudding user response:

Hello and welcome to Stackoverflow!

You are correctly set a new value into the BehaviorSubject, and with: *ngIf="content$"you are just checking that BehaviorSubject exists.

In order to get the content you have to:

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

With let content you can access to your subject's value, in case you have to ;)

You can have more information about on AsyncPipe doc

CodePudding user response:

You need to use the async pipe to read the observable value.

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

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

  • Related