使NbAlertComponent的关闭按钮起作用(关闭警报)的正确方法是什么?

时间:2019-01-19 14:00:30

标签: javascript angular nebular

我正在将nebular用于我的项目,但无法找出如何获取NbAlertComponent的close button来真正关闭警报。通过关闭,我的意思是单击close button后停止显示。我阅读了有关警报组件docs的文档,但没有找到答案。警报组件可以具有属性closable,该属性添加了关闭按钮,并且在单击事件(close)="onClose()"时可以具有事件处理程序。我以这种方式使用它(角度6):

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

在page.component.ts中,如果我有方法onClose,则每当我单击警报close button时它就会触发,但是如何真正关闭它?

// page.component.ts
onClose() {

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

以下是警报组件相关的关闭功能的一些代码:

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

1 个答案:

答案 0 :(得分:1)

在这种情况下,您应该可以像这样使用Angular本身提供的*ngIf指令。

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

另一种适用于多个警报的方法是使警报存在于数组中。

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

这些方法的好处是您不会使警报保持在DOM内部