在带有模板的 Angular ng-bootstrap 模态中,关闭和关闭按钮不起作用

In Angular ng-bootstrap modal with template, close and dismiss buttons not working

我是 angular 的新手,我正在构建中学习。

我需要以编程方式打开具有不同 HTML 内容的模式。

我已经参考了第一个 stackblitz example illustrated in this issue 并创建了一个 ModalComponent(带有名为 <app-modal> 的选择器),这样我就可以在我的应用程序的任何地方创建模态。

现在,我在页面的 <ng-template> 中使用此组件,其中包含不同的 html 内容。

单击主页中的按钮可以正常打开模式,但模式中的关闭和关闭按钮不起作用。

我试着在这里做一个最小的例子:https://stackblitz.com/edit/angular-j1u4fo

如有任何帮助,我们将不胜感激。谢谢。

在您对 openModal 的调用中将 this.m1 替换为 ModalComponent

根据 API documentation,NgbActiveModal 仅在您传入组件而不是模板时起作用。

If you pass a component type as content, then instances of those components can be injected with an instance of the NgbActiveModal class. You can then use NgbActiveModal methods to close / dismiss modals from "inside" of your component.

试试这个

我已经使用 let-c="close" 和 let-d="dismiss"

创建了模态的全局配置

app.component.html

<div class="container-fluid">
<p>Welcome to {{ name }}</p>
<button type="button" (click)="openModal()">Click to open Modal</button>

<!-- Example 1: Passing TemplateRef as custom component -->
  <ng-template #modal1 let-c="close" let-d="dismiss">
    <app-modal [title]="'Title'" [c]="c" [d]="d">
      <img src="https://angular.io/assets/images/logos/angular/angular.png" height="100px" width="100px">
    </app-modal>
  </ng-template>
</div>

modal.component.html

<div class="modal-header">
    <h4 class="modal-title">{{title}}</h4>
    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<div class="modal-body">
    <ng-content></ng-content>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" (click)="c('Close click')">Cancel</button>
</div>

modal.component.ts

import { Component, Input, OnInit } from '@angular/core';

import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';


@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

  @Input() title = `Information`;
  @Input() c;
  @Input() d;

  constructor(
    public activeModal: NgbActiveModal
  ) {}

  ngOnInit() {
  }

}