我有一个Modal的通用组件,我希望来自其他组件的任何数据或消息必须在这个通用模态组件中动态运行,这样我就不必在项目中多次重写模式代码。
我是Angular 4的新手并使用服务方法,所以请查看下面的代码并告诉我如何纠正它以及正确的方法是什么。让下面的任何组件都是任何组件,我希望在特定事件中弹出这个模态,所以请帮助我,就像我如何在特定事件上发出这个模态一样。
modalcomponent.ts
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import { ModalService } from '../../../_services/modal-loader.service';
@Component({
selector: 'app-modal',
templateUrl: "./modal.component.html",
encapsulation: ViewEncapsulation.None,
})
export class ModalComponent implements OnInit {
closeResult: string;
constructor( private modalService: NgbModal,
private ms:ModalService) {
}
ngOnInit() {
}
open(content) {
this.modalService.open(content).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
console.log();
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
modalcomponent.html
<ng-template #content let-c="close" let-d="dismiss">
<div class="modal-header">
<h4 class="modal-title">{{ms.modalTitle}}</h4>
<button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>{{ms.modalBody}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
</div>
</ng-template>
<button class="btn btn-lg btn-outline-primary" (click)="open(content)">Launch demo modal</button>
modalservice.service.ts
import { Injectable } from "@angular/core";
//import { Http } from "@angular/http";
@Injectable()
export class ModalService {
modalTitle:String='Default Title';
modalBody:String='Default Body';
openModal:boolean=true;
createModal(modalTitle:String, modalBody:String, openModal:boolean ){
this.modalTitle = modalTitle;
this.openModal = openModal;
this.openModal=openModal;
}
}
AnyComponent.component.ts
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import { ModalService } from '../../../_services/modal-loader.service';
@Component({
selector: 'app-any',
templateUrl: "./any.component.html",
encapsulation: ViewEncapsulation.None,
})
export class AnyComponent implements OnInit {
closeResult: string;
constructor( private modalService: NgbModal,
private ms:ModalService) {
}
ngOnInit() {
}
让下面的AnyComponent成为任何组件,我希望在特定事件中弹出这个模态,所以请帮助我,就像我如何在特定事件上发出这个模态一样。