在angular 2中,有没有什么不那么复杂的方法来创建一个确认对话框, idea 是点击一个项目,然后显示一个弹出窗口或模式来确认它的删除,我从这里try 了angular 2模式angular2-modal,但我不知道如果你确认或取消它做了一些事情,该怎么做.
this.modal.open(MyComponent);
我不想创建另一个组件只是为了显示一个确认框,这就是为什么我要问.
在angular 2中,有没有什么不那么复杂的方法来创建一个确认对话框, idea 是点击一个项目,然后显示一个弹出窗口或模式来确认它的删除,我从这里try 了angular 2模式angular2-modal,但我不知道如果你确认或取消它做了一些事情,该怎么做.
this.modal.open(MyComponent);
我不想创建另一个组件只是为了显示一个确认框,这就是为什么我要问.
Method 1个
一种简单的确认方法是使用本机浏览器确认alert .
<button type=button class="btn btn-primary" (click)="clickMethod('name')">Delete me</button>
组件方法可以如下所示.
clickMethod(name: string) {
if(confirm("Are you sure to delete "+name)) {
console.log("Implement delete functionality here");
}
}
Method 2
获得简单确认对话框的另一种方法是使用Angular bootstrap 组件,如ng-bootstrap或ngx-bootstrap.您只需安装组件并使用modal组件即可.
Method 3
下面提供的是使用我在项目中实现的angular2/material
实现简单确认弹出窗口的另一种方法.
应用程序.单元ts
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';
@NgModule({
imports: [
...
FormsModule,
ReactiveFormsModule
],
declarations: [
...
ConfirmationDialog
],
providers: [ ... ],
bootstrap: [ AppComponent ],
entryComponents: [ConfirmationDialog]
})
export class AppModule { }
confirmation-dialog.ts
import { Component, Input } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';
@Component({
selector: 'confirm-dialog',
templateUrl: '/app/confirm-dialog/confirmation-dialog.html',
})
export class ConfirmationDialog {
constructor(public dialogRef: MdDialogRef<ConfirmationDialog>) {}
public confirmMessage:string;
}
confirmation-dialog.html
<h1 md-dialog-title>Confirm</h1>
<div md-dialog-content>{{confirmMessage}}</div>
<div md-dialog-actions>
<button md-button style="color: #fff;background-color: #153961;" (click)="dialogRef.close(true)">Confirm</button>
<button md-button (click)="dialogRef.close(false)">Cancel</button>
</div>
应用程序.组成部分html
<button (click)="openConfirmationDialog()">Delete me</button>
app.component.ts
import { MdDialog, MdDialogRef } from '@angular/material';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';
@Component({
moduleId: module.id,
templateUrl: '/app/应用程序.组成部分html',
styleUrls: ['/app/main.css']
})
export class AppComponent implements AfterViewInit {
dialogRef: MdDialogRef<ConfirmationDialog>;
constructor(public dialog: MdDialog) {}
openConfirmationDialog() {
this.dialogRef = this.dialog.open(ConfirmationDialog, {
disableClose: false
});
this.dialogRef.componentInstance.confirmMessage = "Are you sure you want to delete?"
this.dialogRef.afterClosed().subscribe(result => {
if(result) {
// do confirmation actions
}
this.dialogRef = null;
});
}
}
index.html=>;添加到以下样式表
<link rel="stylesheet" href="node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css">