如何在Angular不同组件中渲染ng-template?
解决Angular跨组件渲染的问题
问题原因
你遇到的错误是因为content是Test组件内部的模板引用变量,组件A的模板作用域无法直接访问到这个变量,所以Angular提示content不存在于AComponent中。
解决方案
要实现跨组件渲染Test组件内的模板,需要让Test组件将内部的模板引用暴露出来,再在组件A中通过Test组件的实例访问该模板:
步骤1:修改Test组件,暴露内部模板引用
在test.ts中,通过@ViewChild获取#content模板的引用,并将其作为公共属性对外暴露:
import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'; @Component({ selector: 'test', templateUrl: './test.component.html', standalone: true, }) export class TestComponent implements OnInit { // 获取内部模板引用并暴露 @ViewChild('content') content!: TemplateRef<any>; ngOnInit(): void {} }
步骤2:在组件A中通过Test组件实例访问模板
在A.html中,先给Test组件添加一个模板引用变量(比如#testComp),然后通过这个变量访问Test组件暴露的content模板:
<!-- 声明Test组件的实例引用 --> <test #testComp></test> <!-- 通过实例引用访问内部模板并渲染 --> <ng-container *ngTemplateOutlet="testComp.content"></ng-container>
这样就能在组件A中成功渲染Test组件内的<ng-template>内容了。
内容的提问来源于stack exchange,提问作者user6781
相关产品推荐
相关产品推荐

