首页 文章

如何在Angular2中创建Dialog服务

提问于
浏览
3

在Angular 2中,似乎任何和所有DOM操作都是由组件或指令执行的 . 我已经习惯了Angular 1,但是在某些服务中创建和管理自己的DOM元素是相当普遍的 . 最值得注意的是对话 .

在过去,有可能创建一个Angular 1服务 ConfirmationService ,其函数 Confirm() 返回 Promise<bool> ,向用户显示按下是或否的对话框,这解决了承诺 .

这些对话服务(例如UI Bootstrap ModalNgDialog)通常通过注入 $document$compile$parse 服务并动态创建和注入DOM元素来工作 .

我想要防止必须创建一个必须添加到需要确认的任何组件的 ConfirmationComponent (部分原因是它也可能是需要确认的另一个服务,而且确认只是一个有用的示例)

无论如何,一些帮助/指针将不胜感激 . 提前致谢 .

4 回答

  • 0

    我跑过this link . 虽然我还没有尝试过,但看起来解决方案是像往常一样创建一个Component,以及一个使用该组件的服务:

    @Injectable()
    export class DialogService {  
      constructor(private modalService: NgbModal) {}
    
      public confirm() {
        const modalRef = this.modalService.open(DialogComponent);
        modalRef.componentInstance.name = "Discard Changes?";
        modalRef.componentInstance.message = "Are you sure you want to discard your changes?";
        modalRef.componentInstance.changeRef.markForCheck();
        return modalRef.result;
      }
    }
    

    诀窍是确保从主@NgModule引用DialogComponent:

    NgModule({imports:[...],声明:[DialogComponennt],bootstrap:[AppComponent],providers:[DialogService],entryComponents:[DialogComponent]})

  • 0

    如果您对sweetalert2具有依赖性,则对话服务变得非常简单:

    import { Injectable } from '@angular/core';
    import { default as swal } from 'sweetalert2';
    
    @Injectable()
    export class DialogService {
        confirm(title: string, message: string) {
            return swal({
                title: title,
                text: message,
                type: 'warning',
                showCancelButton: true
            });
        };
    }
    
  • 4

    Angular Material有一个对话框,以“角度”类型的方式工作,并支持多个打开的对话框(不确定为什么,但确实如此) .

    https://material.angular.io/components/dialog/overview

  • 1
    import { Observable } from 'rxjs/Rx';
    import { DialogsFormComponent } from  './dialogs-form.component';
    import { MatDialogRef, MatDialog, MatDialogConfig } from '@angular/material';
    import { Injectable } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';
    
    @Injectable() 
    exprt class DialogsFormService {
    constructor(private dialog: MatDialog, private fb: FormBuilder) { }
    public config(title: string, fields: any, formGroup: any): Observable<boolean> {
    let dialogRef: MatDialogRef<DialogsFormComponent>;
    dialogRef = this.dialog.open(DialogsFormComponent, { width: '600px
    '});
    if (formGroup instanceof FormGroup) {
    dialogRef.componentInstance.modalForm = formGroup;
    } else {
    dialogRef.componentInstance.modalForm = this.fb.group(formGroup);
    }
    dialogRef.componentInstance.title = title;
    dialogRef.componentInstance.fields = fields;
    return dialogRef.afterClosed();
    }
    }
    

    component.ts

    import { Validators } from '@angular/forms';
    
    export class YourComponent {
    constructor (private dialogsFormService: DialogFormService) {}
    openDialog() {
    const title =  'Your Title';
    const type = 'your type you can control on dialog html';
    const fields = dialogFieldOptions;
    const formGroup = {
    prority:['', Validators.required ],
    type: ['', Validators.required ],
    message: ['', Validators.required]
    };
    this.dialogsFormService.confirm(title, fields, formGroup)
    .subscribe((res) => {
    if (response != undefined) {
    // do some things
    }
    });
    }
    }
    const dialogFieldOptions = [
    {
    'label': 'you lable',
    'type': 'radio',
    'name': 'your name',
    'option': ['option1', 'option2'],
    'required': true;
    }
    ];
    

    dialog-form.component.ts

    import { component, Inject } from '@angular/core';
    import { MatDialogRef } from '@angular/material';
    import { FormGroup } from '@angular/forms';
    @Component({ templateUrl:'./dialogs-form.component.html'})
    export class DialogsFormComponent {
    public title: string;
    public fields: any;
    public modalForm: any;
    private markFormAsTouched (formGroup: FormGroup) {
    (<any>Object).values(formGroup.constrols).forEach(control => {
    control.markAsTouched();
    if (control.controls) {
    this.markFormAsTouched(control);
    }
    });
    }
    constructor(public dialogRef: MatDialogRef<DialogsFormComponent>) { }
    onSubmit(mForm, dialog) {
    if (mForm.valid) {
    dialog.close(mForm.value);
    } else {
    this.markFormAsTouched(mForm);
    }
    }
    }
    

    dialog-form.component.html

    <form (ngSubmit) = "onSubmit(modelForm, dialogRef)" [formGroup]= "modalForm">
    <mat-dialog-content>
    <selection *ngIf = "field.type ==== 'radio'">
    <label> field.label</label>
    <mat-radio-group formControlName="field.name" required = "field.required">
    <mat-radio-button *ngFor="let option of field.options" [value]= "option">
    {{option}}</mat-radio-button>
    </mat-radio-group>
    </selection>
    </mat-dialog-content>
    <mat-dialog-actions>
    <button type="button" mat-raised-button (click)="dialogRef.close()"> Cancle</button>
    <button type="submit" mat-raised-button> Submit</button>
    </mat-dialog-actions>
    </form>
    

相关问题