简体   繁体   English

如何在 Angular2 中创建对话服务

[英]How to create a Dialog service in Angular2

In Angular 2 it seems any and all DOM manipulations are performed by components or directives.在 Angular 2 中,似乎所有 DOM 操作都是由组件或指令执行的。 I'm used to Angular 1 however in which it was reasonably common to have certain services that created and managed their own DOM elements;然而,我已经习惯了 Angular 1,其中某些服务创建和管理自己的 DOM 元素是相当普遍的; most notably dialogs.最显着的对话。

In the past it was possible to for instance create an Angular 1 service ConfirmationService with a function Confirm() that returned a Promise<bool> that showed the user a dialog to press either yes or no on, which resolved the promise.在过去,例如可以创建一个 Angular 1 服务ConfirmationService ,其函数Confirm()返回一个Promise<bool> ,向用户显示一个对话框,按是或否,这解决了承诺。

These dialog services (for instance UI Bootstrap Modal or the NgDialog ) generally work by injecting the $document , $compile and $parse services and create and inject DOM elements on the fly.这些对话框服务(例如UI Bootstrap ModalNgDialog )通常通过注入$document$compile$parse服务来工作,并动态创建和注入 DOM 元素。

I'm having difficulties finding out what the recommended Angular 2 approach is to creating such a service.我很难找出推荐的 Angular 2 方法是什么来创建这样的服务。 If at all possible I'd like to prevent having to create a ConfirmationComponent that has to be added to any component that needs to ask for confirmation (partly because it can also be another service that needs the confirmation and that confirmation is but one example where this is useful)如果可能的话,我想避免创建一个必须添加到任何需要确认的组件中的ConfirmationComponent (部分原因是它也可以是另一个需要确认的服务,而该确认只是一个示例,其中这很有用)

Anyway, some help/pointers would be greatly appreciated.无论如何,将不胜感激一些帮助/指针。 Thanks in advance.提前致谢。

If you're ok taking a dependency on sweetalert2 , a dialog service becomes pretty simple:如果您可以依赖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
        });
    };
}

I just ran across this link .我刚刚遇到了这个链接 While I haven't tried it yet, it looks like the solution is to create a Component as usual, and a service that uses that component like so:虽然我还没有尝试过,但看起来解决方案是像往常一样创建一个组件,以及一个使用该组件的服务,如下所示:

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

The trick is to make sure to reference the DialogComponent from your main @NgModule:诀窍是确保从您的主@NgModule 中引用 DialogComponent:

@NgModule({
  imports: [...], 
  declarations: [ DialogComponent ],
  bootstrap:    [ AppComponent ],
  providers: [ DialogService],
  entryComponents: [DialogComponent]
})

Angular Material has a dialog box that works in an 'angular' type of way and supports multiple open dialogs (not really sure why but it does). Angular Material 有一个对话框,它以“角度”类型的方式工作,并支持多个打开的对话框(不确定为什么,但确实如此)。

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

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组件.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 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 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM