[Angular] Angular Advanced Features - ng-template , ng-container, ngTemplateOutlet
Previously we have tab-panel template defined like this:
<ul class="tab-panel-buttons" *ngIf="tabs"> <li [ngClass]="{selected: tab.selected}" (click)="selectTab(tab)" *ngFor="let tab of tabs;">{{tab.title}} </li> </ul> <ng-content></ng-content>
So the template is not overrideable. If we want later able to pass in a different template, we need to use some advanced features from Angular.
ng-template: We can wrap the whole header into <ng-template>, by defualt, ng-template will not render to the DOM.
<ng-template #defaultTabHeader> <ul class="tab-panel-buttons" *ngIf="tabs"> <li [ngClass]="{selected: tab.selected}" (click)="selectTab(tab)" *ngFor="let tab of tabs;">{{tab.title}} </li> </ul> </ng-template>
To be able to render the template to the DOM; we need to use <ng-content>:
<ng-template #defaultTabHeader let-tabs="tabsX"> <ul class="tab-panel-buttons" *ngIf="tabs"> <li [ngClass]="{selected: tab.selected}" (click)="selectTab(tab)" *ngFor="let tab of tabs;">{{tab.title}} </li> </ul> </ng-template> <ng-content *ngTemplateOutlet="defaultTabHeader; context: tabsContext"></ng-content> <ng-content></ng-content>
import {AfterContentInit, Component, ContentChildren, OnInit, QueryList} from '@angular/core'; import {AuTabComponent} from '../au-tab/au-tab.component'; @Component({ selector: 'au-tab-panel', templateUrl: './au-tab-panel.component.html', styleUrls: ['../tab-panel.component.scss'] }) export class AuTabPanelComponent implements OnInit, AfterContentInit { @ContentChildren(AuTabComponent) tabs: QueryList<AuTabComponent>; constructor() { } ngOnInit() { } ngAfterContentInit(): void { const selectedTab = this.tabs.find(tab => tab.selected); if(!selectedTab && this.tabs.first) { this.tabs.first.selected = true; } } selectTab(tab: AuTabComponent) { this.tabs.forEach(t => t.selected = false); tab.selected = true; } get tabsContext() { return { tabsX: this.tabs }; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2013-06-20 【大型网站架构 原理】1. 负载均衡和冗余技术