使用ngx BsModalService的通用模式服务

时间:2018-08-29 14:26:46

标签: angular ngx-bootstrap-modal

我正在尝试使用BsModalService为应用程序创建一个通用模态组件。 该组件将具有不同的方法,其中包含不同的标题和配置。并且可以从任何其他组件中使用。

模态组件ts文件。

import { Component, OnInit, AfterViewInit, } from '@angular/core';
import { BsModalRef,BsModalService } from 'ngx-bootstrap';

@Component({
  selector: 'app-modal',
  templateUrl: './app-modal.component.html',
  styleUrls: ['./app-modal.component.scss'],
})
export class AppModalComponent implements OnInit, AfterViewInit {
  public modalRef: BsModalRef;
  constructor(private modalService: BsModalService) {
    console.log(`ngAfterViewInit - modaldiretive is---`);
  }
  ngOnInit() {

  }
  confirmationModal(){
    const initialState = {
            title: 'Confirmation',
            message:'Are you sure, you want to delete this campaign?'
    };
    this.modalRef = this.modalService.show(AppModalComponent, {
      class: 'modal-dialog-centered', ignoreBackdropClick :true,initialState 
    });
  }
  **close(){
    this.modalRef.hide();
  }**

  ngAfterViewInit() {
    console.log(`ngAfterViewInit - modaldiretive is ${this}`);
  }
}

html。

<div class="modal-header">
  <h4 class="modal-title pull-left">{{title}}</h4>
  <button type="button" class="close pull-right" aria-label="Close" (click)="close()">
    <span aria-hidden="true">&times;</span>
  </button>
</div>
<div class="modal-body">
  {{message}}
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-default" (click)="close()">Yes</button>
  <button type="button" class="btn btn-default" (click)="close()">No</button>
</div>

使用其他组件。 other.component.ts

import { Component } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap';
import { AppModalComponent } from 'app/core/modal/app-modal.component';
@Component({
  selector: 'details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss']
})
export class DetailsComponent{
constructor() {

}
 removeDetails() {
      this.appModal.confirmationModal();
 }
}

在其他组件中单击removeDetails时,我可以获取确认模态,但是在关闭时抛出错误this.modalRef未定义; 有人可以帮我解决这个问题吗,如果我的方法是正确的,可以隔离modalComponent和其他组件。**

0 个答案:

没有答案