Search code examples
angularng-bootstrap

How to Reshow ngbAlert (Bootstrap widgest for Angular) message again after dismissing it


I am using ngbAlert for Angular. I am showing a alert if my backend API fails.

<ngb-alert class="veri-alert" [type]="alert.type" [dismissible]="true" *ngIf="showErrorAlert">
<span class="icon icon-alert-dark"></span>
<span class="pl-2">{{ alert.message }}</span>
</ngb-alert>

enter image description here

If the API fails I am making showErrorAlert true and the alert is shown as expected. Now if the user clicks on the 'x' button in alert-box, the alert closes as expected. Now, If the user again makes an API call to backend by clicking continue button without refreshing and again the API fails, I do make showErrorAlert as true again. But now, the ngbAlert is not shown.

How can I make the ngbAlert to show again?


Solution

  • Please find below a working example, where the closing of the alert works fine. I added the event (closed)="showErrorAlert = false" to the HTML and it started working fine!

    html

    <ngb-alert
      class="veri-alert"
      [type]="alert.type"
      [dismissible]="true"
      *ngIf="showErrorAlert"
      #staticAlert
      (closed)="showErrorAlert = false"
    >
      <span class="icon icon-alert-dark"></span>
      <span class="pl-2">{{ alert.message }}</span>
    </ngb-alert>
    
    <button (click)="clickAction()">open alert</button>
    

    ts

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap';
    
    @Component({
      selector: 'ngbd-alert-basic',
      standalone: true,
      imports: [NgbAlertModule, CommonModule],
      templateUrl: './alert-basic.html',
    })
    export class NgbdAlertBasic {
      showErrorAlert = false;
      alert = {
        type: 'success',
        message: 'it is working!',
      };
    
      clickAction() {
        this.showErrorAlert = true;
      }
    }
    

    stackblitz