Error: ViewContainerRef.insert() is not a function when trying to add embeddedview into <ng-container>

Error: ViewContainerRef.insert() is not a function when trying to add embeddedview into <ng-container>

我正在尝试按照下面的指南(使用 ng-template 的部分)在我的应用程序中实现模式

https://blog.bitsrc.io/creating-modals-in-angular-cb32b126a88e#:~:text=Different%20methods%20and%20tools%20for%20building%20modals%20in%20Angular&text=Modals%20are%20one%20of,already%20heavy%20with%20HTML%20elements.

问题是,每当我尝试单击按钮打开模式时,控制台都会出现错误: “this.vc.insert 不是函数”。我读过我们应该使用 ngAfterViewInit 挂钩,但我不确定如何应用它,因为我只希望模式在用户单击按钮时显示,而不是在 ngAfterViewInit 触发时显示。

下面是一些代码片段

.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 :)

@ViewChild('vc') vc: ViewContainerRef; 更改为 @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef; 即可正常工作。

Stackblitz eg.

使用 @ViewChild('vc') vc: ViewContainerRef; 使 this.vc 成为 ElementRef,而不是预期的 ViewContainerRef。因此 ElementRef this.vc 没有名为 insert.

的方法

使用 @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;、Angular 显式为您提供与 #vc 本地引用关联的 ViewContainerRef