【发布时间】:2020-10-18 12:00:15
【问题描述】:
我正在尝试按照下面的指南(使用 ng-template 的部分)在我的应用中实现模式
问题是,每当我尝试单击按钮打开模式时,我都会在控制台中收到错误消息: “this.vc.insert 不是函数”。我读过我们应该使用 ngAfterViewInit 钩子,但我不确定如何应用它,因为我只希望模式在用户单击按钮时显示,而不是在 ngAfterViewInit 触发时显示。
下面是一些代码sn-ps
.ts 文件
import { Component, OnInit, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-browse-food',
templateUrl: './browse-food.component.html',
styleUrls: ['./browse-food.component.css']
})
export class BrowseFoodComponent implements OnInit {
constructor() {
}
ngOnInit() {
// unrelated code
}
@ViewChild('orderModal') orderModal: TemplateRef<any>;
@ViewChild('vc') vc: ViewContainerRef;
openModal() {
let view = this.orderModal.createEmbeddedView(null);
this.vc.insert(view);
}
closeModal() {
this.vc.clear();
}
html
<button (click)="openModal()">Open Modal</button>
<ng-container #vc></ng-container>
<ng-template #orderModal>
<div class="modal">
<div class="modal-content">
<div class="modal-header">
<i (click)="closeModal()"></i>
</div>
<div class="modal-body">
</div>
</div>
</div>
</ng-template>
感谢您的帮助,TIA :)
【问题讨论】: