如何在Angular2中创建Dialog服务

时间:2016-09-22 08:43:18

标签: javascript angular

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

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

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

我很难找到推荐的Angular 2方法来创建这样的服务。如果可能的话,我想防止必须创建一个必须添加到需要确认的任何组件的ConfirmationComponent(部分原因是它也可能是需要确认的另一个服务,并且确认是但这是一个有用的例子)

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

4 个答案:

答案 0 :(得分:4)

如果您可以依赖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
        });
    };
}

答案 1 :(得分:1)

我刚跑过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({   进口:[...],   声明:[DialogComponennt],   bootstrap:[AppComponent],   提供者:[DialogService],   entryComponents:[DialogComponent] })

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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;
}
];

对话框的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);
}
}
}

对话框的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>