javascript - 使 NbAlertComponent 的关闭按钮起作用的正确方法是什么(关闭警报)
问题描述
我正在为我的项目使用nebular,但无法找到如何让close button
NbAlertComponent 真正关闭警报。通过关闭我的意思是点击后停止显示close button
。我阅读了有关警报组件文档的文档,但没有找到答案。Alert 组件可以有属性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
,它会在我每次点击 alert 时触发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();
};
解决方案
在这种情况下,您应该能够*ngIf
像这样使用 Angular 本身提供的指令。
// 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 中
推荐阅读
- python - n 维(n>1)numpy 数组中的 A[i] 和 A[i,:] 有什么区别?
- mysql - MySQL group by with time diff
- android - Search view onQueryTextChange issue
- javascript - Vue中的全局组件注册使用
- php - 连接数据库时如何提供凭据?
- node.js - NPM中以下行的含义是什么?
- sql-server - 静默安装 Microsoft Report Builder 3.0 失败
- html - 将鼠标悬停在 li 上时,如何仅使用左侧图像幻灯片
- apache-spark - 如何将过滤功能应用于 org.apache.spark.rdd.RDD[Array[Byte]]
- wpf - 使用 MVVM 在 WPF 中进行动态验证?