当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《Angular2简单的方法来进行确认对话》经验,为你挑选了4个好方法。

是否有任何不那么复杂的方法在角度2中进行确认对话,想法是点击一个项目,然后显示一个弹出窗口或模态以确认其删除,我尝试角度2模态从这里angular2-modal,但如果你确认或取消它,我不知道如何做到这一点.点击功能工作正常,唯一的问题是我不太清楚如何使用它.我还有另一个带有相同插件的模态,与我使用的不同.

this.modal.open(MyComponent);

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



1> Philip John..:

方法1

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


组件方法可以如下所示.

clickMethod(name: string) {
  if(confirm("Are you sure to delete "+name)) {
    console.log("Implement delete functionality here");
  }
}

方法2

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

    使用ng-bootstrap的模态示例

    使用ngx-bootstrap的模态示例.

方法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) {}

  public confirmMessage:string;
}

确认-dialog.html

Confirm

{{confirmMessage}}

app.component.html


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;

  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 =>在样式表后面添加了




2> 小智..:

您可以在函数内部使用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> tilo..:

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

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

}

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

}

确认-dialog.component.html


  
  

使用如下对话框:

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



4> 小智..:

更新:Plunkr补充道

我一直在寻找在所有论坛上的解决方案,但没有找到,所以找到与老同学JavaScript回调函数的解决方案:-)这是一个非常简单和干净的方式来创建一个确认对话框,设置回呼功能都YESNO点击事件.
我使用了Bootrap CSS for Modal和一个带有rxjs主题的警报服务.

这是我的alert.component.html

        

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();
          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 {
             return this.subject.asObservable();
          }
       }

从任何组件调用该函数

           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/

推荐阅读
殉情放开那只小兔子
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有