首页 文章

Angular 2简单的方法来进行确认对话

提问于
浏览
33

是否有任何不那么复杂的方式在角度2中进行确认对话,想法是点击一个项目,然后显示一个弹出窗口或模态以确认其删除,我尝试从这里angular2-modal角度2模态,但我不't know how to make that if you confirm or cancel it does something. the click function works fine, the only problem is that I don' t太了解如何使用它 . 我还有另一个带有相同插件的模态,与我使用的不同 .

this.modal.open(MyComponent);

而且我不想创建另一个组件只是为了显示一个确认框,这就是我要问的原因 .

7 回答

  • 75

    为了在多模块应用程序中重用单个确认对话框实现,该对话框必须在单独的模块中实现 . 这是使用Material Design和FxFlex执行此操作的一种方法,尽管这两种方法都可以修剪或替换 .

    首先是共享模块(./app.module.ts):

    import {NgModule} from '@angular/core';
    import {CommonModule} from '@angular/common';
    import {MatDialogModule, MatSelectModule} from '@angular/material';
    import {ConfirmationDlgComponent} from './confirmation-dlg.component';
    import {FlexLayoutModule} from '@angular/flex-layout';
    
    @NgModule({
       imports: [
          CommonModule,
          FlexLayoutModule,
          MatDialogModule
       ],
       declarations: [
          ConfirmationDlgComponent
       ],
       exports: [
          ConfirmationDlgComponent
       ],
       entryComponents: [ConfirmationDlgComponent]
    })
    
    export class SharedModule {
    }
    

    对话框组件(./confirmation-dlg.component.ts):

    import {Component, Inject} from '@angular/core';
    import {MAT_DIALOG_DATA} from '@angular/material';
    
    @Component({
       selector: 'app-confirmation-dlg',
       template: `
          <div fxLayoutAlign="space-around" class="title colors" mat-dialog-title>{{data.title}}</div>
          <div class="msg" mat-dialog-content>
             {{data.msg}}
          </div>
          <a href="#"></a>
          <mat-dialog-actions fxLayoutAlign="space-around">
             <button mat-button [mat-dialog-close]="false" class="colors">No</button>
             <button mat-button [mat-dialog-close]="true" class="colors">Yes</button>
          </mat-dialog-actions>`,
       styles: [`
          .title {font-size: large;}
          .msg {font-size: medium;}
          .colors {color: white; background-color: #3f51b5;}
          button {flex-basis: 60px;}
       `]
    })
    export class ConfirmationDlgComponent {
       constructor(@Inject(MAT_DIALOG_DATA) public data: any) {}
    }
    

    然后我们可以在另一个模块中使用它:

    import {FlexLayoutModule} from '@angular/flex-layout';
    import {NgModule} from '@angular/core';
    import {GeneralComponent} from './general/general.component';
    import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
    import {CommonModule} from '@angular/common';
    import {MaterialModule} from '../../material.module';
    
    @NgModule({
       declarations: [
          GeneralComponent
       ],
       imports: [
          FlexLayoutModule,
          MaterialModule,
          CommonModule,
          NgbModule.forRoot()
       ],
       providers: []
    })
    export class SystemAdminModule {}
    

    组件的单击处理程序使用对话框:

    import {Component} from '@angular/core';
    import {ConfirmationDlgComponent} from '../../../shared/confirmation-dlg.component';
    import {MatDialog} from '@angular/material';
    
    @Component({
       selector: 'app-general',
       templateUrl: './general.component.html',
       styleUrls: ['./general.component.css']
    })
    export class GeneralComponent {
    
       constructor(private dialog: MatDialog) {}
    
       onWhateverClick() {
          const dlg = this.dialog.open(ConfirmationDlgComponent, {
             data: {title: 'Confirm Whatever', msg: 'Are you sure you want to whatever?'}
          });
    
          dlg.afterClosed().subscribe((whatever: boolean) => {
             if (whatever) {
                this.whatever();
             }
          });
       }
    
       whatever() {
          console.log('Do whatever');
       }
    }
    

    只是使用 this.modal.open(MyComponent); ,因为你赢了't return you an object whose events you can subscribe to which is why you can' t得到它做一些事情 . 此代码创建并打开一个对话框,其中包含我们可以订阅的事件 .

    如果你修剪css和html这实际上是一个简单的组件,但是自己编写它可以让你控制它的设计和布局,而预先编写的组件需要更加重量级才能给你控制 .

  • 9

    您可以在函数内部使用window.confirm并结合if条件

    delete(whatever:any){
        if(window.confirm('Are sure you want to delete this item ?')){
        //put your delete method logic here
       }
    }
    

    当您调用delete方法时,它将弹出一条确认消息,当您按下ok时,它将执行if条件内的所有逻辑 .

  • 3

    使用javascript的本机确认功能和自定义Angular指令,这是一个非常不同的看法 . 它非常灵活,非常轻巧:

    用法:

    <button (hrsAreYouSure) (then)="confirm(arg1)" (else)="cancel(arg2)">
      This will execute confirm if user presses Ok on the confirmation dialog, or cancel if they
      hit Cancel
    </button>
    

    指示:

    import {Directive, ElementRef, EventEmitter, Inject, OnInit, Output} from '@angular/core';
    
    @Directive({
      selector: '[hrsAreYouSure]'
    })
    
    export class AreYouSureDirective implements OnInit {
    
      @Output() then = new EventEmitter<boolean>();
      @Output() else = new EventEmitter<boolean>();
    
      constructor(@Inject(ElementRef) private element: ElementRef) { }
    
      ngOnInit(): void {
        const directive = this;
        this.element.nativeElement.onclick = function() {
          const result = confirm('Are you sure?');
          if (result) {
            directive.then.emit(true);
          } else {
            directive.else.emit(true);
          }
        };
      }
    }
    
  • 0

    UPDATE: Plunkr added

    我在所有论坛上都寻找解决方案,但没有找到,所以找到了Old School Javascript Callback函数的解决方案:-)这是一个非常简单干净的方法来创建一个确认对话框并为 YESNO 点击设置回调函数事件 .
    我使用了Bootrap CSS for Modal和一个警报服务与rxjs Subject .

    这是我的 alert.component.html

    <div *ngIf="message.type == 'confirm'"  class="modal-body">
                <div class="row">
                    <div class="col-md-12">
                        <h3 class="text-center">{{message.text}}</h3>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <p class="text-center">
                            <a (click)="message.noFn()">
                                <button class="btn btn-pm">No</button>
                            </a>
                            <a (click)="message.siFn()">
                                <button  class="btn btn-sc" >Yes</button>
                            </a>
                        </p>
                    </div>
                </div>
             </div>
    

    alert.component.ts

    export class AlertComponent {
        message: any;
        constructor(
          public router: Router, 
          private route: ActivatedRoute, 
          private alertService: AlertService,
       ) { }
       ngOnInit() {
        //this function waits for a message from alert service, it gets 
        //triggered when we call this from any other component
        this.alertService.getMessage().subscribe(message => {
            this.message = message;
        });
    }
    

    最重要的部分就在这里! alert.service.ts

    import { Injectable } from '@angular/core'; 
         import { Router, NavigationStart } from '@angular/router'; 
         import { Observable } from 'rxjs'; 
         import { Subject } from 'rxjs/Subject';
         @Injectable() export class AlertService {
              private subject = new Subject<any>();
              constructor(){}
              confirm(message: string,siFn:()=>void,noFn:()=>void){
                this.setConfirmation(message,siFn,noFn);
              }
              setConfirmation(message: string,siFn:()=>void,noFn:()=>void) {
                let that = this;
                this.subject.next({ type: "confirm",
                            text: message,
                            siFn:
                            function(){
                                that.subject.next(); //this will close the modal
                                siFn();
                            },
                            noFn:function(){
                                that.subject.next();
                                noFn();
                            }
                         });
    
                     }
    
              getMessage(): Observable<any> {
                 return this.subject.asObservable();
              }
           }
    

    Call the function from any component

    this.alertService.confirm("You sure Bro?",function(){
                  //ACTION: Do this If user says YES
                },function(){
                  //ACTION: Do this if user says NO
                })
    

    Plunkr https://embed.plnkr.co/vWBT2nWmtsXff0MXMKdd/

  • 1

    Method 1

    一种简单的确认方法是使用本机浏览器确认警报 . 模板可以有一个按钮或链接 .

    <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

    获得简单确认对话框的另一种方法是使用角度引导程序组件,如ng-bootstrapngx-bootstrap . 您只需安装组件并使用模态组件即可 .

    Method 3

    下面提供了另一种使用我在项目中实现的 angular2/material 实现简单确认弹出窗口的方法 .

    app.module.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 { }
    

    确认-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;
    }
    

    确认-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>
    

    app.component.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/app.component.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">
    
  • 11

    你可以使用sweetalert:https://sweetalert.js.org/guides/

    npm install sweetalert --save
    

    然后,只需将其导入您的应用程序:

    import swal from 'sweetalert';
    

    如果传递两个参数,第一个将是模态的 Headers ,第二个是文本 .

    swal("Here's the title!", "...and here's the text!");
    
  • 19

    我参加派对的时间已经很晚了,但这是使用ng-bootstrap的另一个实现:https://stackblitz.com/edit/angular-confirmation-dialog

    confirmation-dialog.service.ts

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    
    import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
    
    import { ConfirmationDialogComponent } from './confirmation-dialog.component';
    
    @Injectable()
    export class ConfirmationDialogService {
    
      constructor(private modalService: NgbModal) { }
    
      public confirm(
        title: string,
        message: string,
        btnOkText: string = 'OK',
        btnCancelText: string = 'Cancel',
        dialogSize: 'sm'|'lg' = 'sm'): Promise<boolean> {
        const modalRef = this.modalService.open(ConfirmationDialogComponent, { size: dialogSize });
        modalRef.componentInstance.title = title;
        modalRef.componentInstance.message = message;
        modalRef.componentInstance.btnOkText = btnOkText;
        modalRef.componentInstance.btnCancelText = btnCancelText;
    
        return modalRef.result;
      }
    
    }
    

    confirmation-dialog.component.ts

    import { Component, Input, OnInit } from '@angular/core';
    import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
    
    @Component({
      selector: 'app-confirmation-dialog',
      templateUrl: './confirmation-dialog.component.html',
      styleUrls: ['./confirmation-dialog.component.scss'],
    })
    export class ConfirmationDialogComponent implements OnInit {
    
      @Input() title: string;
      @Input() message: string;
      @Input() btnOkText: string;
      @Input() btnCancelText: string;
    
      constructor(private activeModal: NgbActiveModal) { }
    
      ngOnInit() {
      }
    
      public decline() {
        this.activeModal.close(false);
      }
    
      public accept() {
        this.activeModal.close(true);
      }
    
      public dismiss() {
        this.activeModal.dismiss();
      }
    
    }
    

    confirmation-dialog.component.html

    <div class="modal-header">
      <h4 class="modal-title">{{ title }}</h4>
        <button type="button" class="close" aria-label="Close" (click)="dismiss()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        {{ message }}
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-danger" (click)="decline()">{{ btnCancelText }}</button>
        <button type="button" class="btn btn-primary" (click)="accept()">{{ btnOkText }}</button>
      </div>
    

    使用如下对话框:

    public openConfirmationDialog() {
        this.confirmationDialogService.confirm('Please confirm..', 'Do you really want to ... ?')
        .then((confirmed) => console.log('User confirmed:', confirmed))
        .catch(() => console.log('User dismissed the dialog (e.g., by using ESC, clicking the cross icon, or clicking outside the dialog)'));
      }
    

相关问题