可以通过Angular中的ng-template来解决此问题。我们可以在组件中定义一个ng-template,并重用它来渲染页面和模态框。
在组件的HTML文件中,我们首先定义一个ng-template,如下所示:
在页面中,我们可以使用ng-container和ngTemplateOutlet指令来重用此ng-template,如下所示:
在模态框中,我们还需要使用ng-template来定义模态框的内容。我们将模态框的内容包含在一个ng-template中,并在打开模态框时加载它。在模态框组件的HTML文件中,我们可以这样做:
Open Modal
在组件的ts文件中,我们需要通过ViewChild装饰器来获取ng-template元素的引用。我们可以这样做:
import { Component, ViewChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
@ViewChild('myTemplate') myTemplate: TemplateRef;
@ViewChild('modalTemplate') modalTemplate: TemplateRef;
// open modal method here
openModal() {
// load modal content here
}
}
在openModal方法中,我们需要通过模态框组件的服务加载模态框内容,如下所示:
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
constructor(private modalService: NgbModal) {}
openModal() {
const modalRef = this.modal