Home > database >  Manage a boolean value
Manage a boolean value

Time:12-20

In my hmtl I would to show an alert based on value of variable.

so I have in my html:

<div >
                        <div >
                            <div *ngIf="showingUpdateMessage === true"  role="alert">
                                Success.
                            </div>
                            <div *ngIf="showingUpdateMessage === false"  role="alert">
                                Danger
                            </div>
                        </div>
 </div>

<button (click)="onUpdateCustomer(form)">Save

So in my component.ts

export class Page implements OnInit {
    showingUpdateMessage: boolean

updateFunction(form){
 this.showingUpdateMessage = null
 this.service.updateForm(form).subscribe(
 (data) => { this.showingUpdateMessage = true},
 (error) => { this.showingUpdateMessage = false}
 )
}

}

So my problem is that sometimes the alert doesn't appear, so I tried to inizialize the variable to null in the function. But I notice that sometimes alert doesn't show up.

How can I manage a boolean variable, that will be set ,for example, in response to an api call?

CodePudding user response:

You have a change detection issue. Just add this to your code.


constructor(
  // ...
  private cdRef: ChangeDetectorRef
) {}

//..

updateFunction(form){
  this.showingUpdateMessage = null
  this.service.updateForm(form).pipe(
    finalize(() => this.cdRef.detectChanges())
  ).subscribe(
    (data) => { this.showingUpdateMessage = true},
    (error) => { this.showingUpdateMessage = false}
  );
}

CodePudding user response:

you can store the Observable itself inside the variable and use async pipe in the template - this is a better practice

this.showingUpdateMessage$ = this.service.updateForm(form).pipe(mapTo(true));

and inside your template:

<div  *ngIf="showingUpdateMessage$ | async as showUpdateMessage">
                        <div *ngIf="showUpdateMessage"  role="alert">
                            Success.
                        </div>
                        <div *ngIf="!showUpdateMessage"  role="alert">
                            Danger
                        </div>
                    </div>
  • Related