【问题标题】:Error: ViewContainerRef.insert() is not a function when trying to add embeddedview into <ng-container>错误:尝试将嵌入式视图添加到 <ng-container> 时,ViewContainerRef.insert() 不是函数
【发布时间】:2020-10-18 12:00:15
【问题描述】:

我正在尝试按照下面的指南(使用 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 触发时显示。

下面是一些代码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 :)

【问题讨论】:

    标签: angular viewchild


    【解决方案1】:

    @ViewChild('vc') vc: ViewContainerRef; 更改为@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef; 使其工作。

    Stackblitz eg.

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

    使用@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;,Angular 显式地为您提供与#vc 本地引用关联的ViewContainerRefHere's a small and fuller explanation.

    【讨论】:

    • 嗨,Tarun,感谢您的帮助 - 现在完美运行!也为链接+1 :)
    猜你喜欢
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 2012-10-03
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多