1

我正在尝试使用 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>

在其他一些组件中使用。其他.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 is undefined; 有人可以帮我解决这个问题吗,如果我的方法是正确的,可以隔离我的 modalComponent 和其他组件。**

4

0 回答 0