首页 > 解决方案 > 在带有模板的 Angular ng-bootstrap 模态中,关闭和关闭按钮不起作用

问题描述

我是 Angular 的新手,我正在通过构建来学习。

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

我参考了本期中说明的第一个 stackblitz示例创建了一个 ModalComponent(带有名为 的选择器),以便我可以在我的应用程序的任何位置创建模态。<app-modal>

<ng-template>现在,我在我的页面中使用这个组件和不同的 html 内容。

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

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

任何帮助将不胜感激。谢谢。

标签: angulartypescriptangular7ng-bootstrapng-template

解决方案


试试这个

我用 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() {
  }

}

推荐阅读