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

Angular中能否跨组件使用其他组件内定义的ng-template?

How to Use an ng-template from One Angular Component in Another

Absolutely! You can share an ng-template from one component to another in Angular, and your code example is already on the right track. Let me break down this approach clearly, plus add a small improvement for type safety.

Step 1: Define and Pass the Template from the Source Component

In your source component (Component1), first define your ng-template with a template reference variable (using #template1 here). Then pass this reference to the target component (Component2) via an input binding:

@Component({
  selector: 'component1',
  template: `
    <ng-template #template1>
      <div class="test">
        <h1>component 1</h1>
      </div>
    </ng-template>
    <!-- Pass the template reference to Component2 -->
    <component2 [templateRef]="template1"></component2>
  `
})
export class Component1 { }

Step 2: Receive and Render the Template in the Target Component

In Component2, use an @Input() decorator to accept the template reference. To render the template, use Angular's ngTemplateOutlet directive inside an ng-container (which doesn't add extra DOM elements):

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

@Component({
  selector: 'component2',
  template: `
    <!-- Render the incoming template here -->
    <ng-container [ngTemplateOutlet]="templateRef"></ng-container>
  `
})
export class Component2 {
  // Use TemplateRef<any> for better type safety instead of untyped
  @Input() templateRef: TemplateRef<any>;
}

Key Notes:

  • Type Safety: I changed the input property type to TemplateRef<any> instead of an untyped variable—this helps catch errors during development and makes your code more maintainable.
  • ng-container: This is the ideal host for ngTemplateOutlet because it doesn't render any extra HTML elements, keeping your DOM clean.
  • Passing Context (Optional): If you need to pass data to the template later, you can use the ngTemplateOutletContext input to send variables to the template. For example:
    <ng-container [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{ $implicit: 'Hello from Component2' }"></ng-container>
    
    Then in the source template, you can access the context like this:
    <ng-template #template1 let-message>
      <div class="test">
        <h1>component 1</h1>
        <p>{{ message }}</p>
      </div>
    </ng-template>
    

内容的提问来源于stack exchange,提问作者Roberto Carlos Diaz Justicia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:57:19