Angular中能否跨组件使用其他组件内定义的ng-template?
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
ngTemplateOutletbecause 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
ngTemplateOutletContextinput to send variables to the template. For example:
Then in the source template, you can access the context like this:<ng-container [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{ $implicit: 'Hello from Component2' }"></ng-container><ng-template #template1 let-message> <div class="test"> <h1>component 1</h1> <p>{{ message }}</p> </div> </ng-template>
内容的提问来源于stack exchange,提问作者Roberto Carlos Diaz Justicia

