You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular:如何实现两个组件在ng-container中的切换显示?

解决Angular包装组件切换多子组件的问题

核心思路

你之前仅通过@ContentChild获取了单个TemplateRef,自然只能显示一个组件。要实现两个组件的切换,需要分别获取两个子组件对应的模板引用,再通过切换逻辑控制显示目标模板。

具体实现步骤

1. 修改WrapperComponent的TS代码

定义两个@ContentChild装饰器,分别绑定父组件中两个子组件的模板标识,同时调整切换状态变量和方法:

import { Component, ContentChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'app-wrapper',
  templateUrl: './wrapper.component.html',
})
export class WrapperComponent {
  // 获取两个子组件的模板引用,对应父组件中的#comp1和#comp2标识
  @ContentChild('comp1') comp1Template!: TemplateRef<any>;
  @ContentChild('comp2') comp2Template!: TemplateRef<any>;

  // 用字符串标识当前显示的组件,默认显示第一个
  currentDisplay = 'comp1';

  // 切换方法
  toggleComponents() {
    this.currentDisplay = this.currentDisplay === 'comp1' ? 'comp2' : 'comp1';
  }
}

2. 调整WrapperComponent的模板

根据currentDisplay的值,用ngTemplateOutlet渲染对应的模板:

<!-- 切换按钮 -->
<button (click)="toggleComponents()">切换组件</button>

<!-- 渲染对应模板 -->
<ng-container *ngIf="currentDisplay === 'comp1'; else comp2Outlet">
  <ng-container [ngTemplateOutlet]="comp1Template"></ng-container>
</ng-container>

<ng-template #comp2Outlet>
  <ng-container [ngTemplateOutlet]="comp2Template"></ng-container>
</ng-template>

3. 父组件中使用WrapperComponent

在父组件模板里,把两个子组件分别放到带标识的<ng-template>中,传递给包装组件:

<app-wrapper>
  <ng-template #comp1>
    <my-component-1></my-component-1>
  </ng-template>

  <ng-template #comp2>
    <my-component-2></my-component-2>
  </ng-template>
</app-wrapper>

额外说明

如果后续需要支持更多组件,可以改用@ContentChildren(TemplateRef)获取所有模板,再结合自定义指令给每个模板加标识(比如appComponentTab="tab1"),通过标识来区分渲染。但当前场景下,用两个明确的@ContentChild更简单直接。

内容的提问来源于stack exchange,提问作者Andy88

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:15:52