0

I'm using nebular for my project, and cannot find out how to get close button of NbAlertComponent to actually close alert. By closing I mean to stop showing after clicking on close button. I read documentation about alert component docs, but did not found an answer. Alert component can have property closable, which adds close button, and can have event handler when clicked on it (close)="onClose()". I'm using it this way (angular 6):

// page.component.html
<nb-alert status="success" closable (close)="onClose()">
  You have been successfully authenticated!
</nb-alert>

In page.component.ts, if I have a method onClose, it fires every time I click on alert close button, but how to actually close it?

// page.component.ts
onClose() {

  // fires after each click on close button:
  console.log('close button was clicked');
}

Here is some code from alert component related close functionality:

// alert.component.ts
/**
  * Emits when chip is removed
  * @type EventEmitter<any>
  */
  // this is an instance of NbAlertComponent
  this.close = new EventEmitter();

/**
 * Emits the removed chip event
 */
NbAlertComponent.prototype.onClose = function () {
    this.close.emit();
};
Vadi
  • 3,279
  • 2
  • 13
  • 30

1 Answers1

3

In this case you should be able to use the *ngIf directive provided by Angular itself like so.

// page.component.html
<nb-alert status="success" closable (close)="onClose()" *ngIf="alertIsOpen">
  You have been successfully authenticated!
</nb-alert>
alertIsOpen = true;

// page.component.ts
onClose() {
  // fires after each click on close button:
  console.log('close button was clicked');
  this.alertIsOpen = false;
}

Another approach which would also work for multiple alerts would be to have your alerts exist in an array.

// page.component.html
<ng-container *ngFor="alert of alerts">
 <nb-alert status="{{alert.status}}" closable (close)="onClose(alert)">
   {{alert.text}}
 </nb-alert>
</ng-container>
alerts = [
 {
   status: "success",
   text: "You have been successfully authenticated!"
 },
 {
   status: "danger",
   text: "Failed to authenticate!"
 }
]

// page.component.ts
onClose(alert) {
  // fires after each click on close button:
  console.log('close button was clicked');
  this.alerts.splice(this.alerts.indexOf(alert), 1);
}

The benefit of these approaches are that you don't keep the alert existing inside your DOM

Jelle
  • 2,026
  • 1
  • 12
  • 17
  • What if I have several alerts? – Vadi Jan 19 '19 at 14:14
  • @Vadi I updated the answer with a solution that would allow for more alerts without having to separately define `isClosed` variables for them – Jelle Jan 19 '19 at 19:29