[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
    };
  }

}
复制代码

 

posted @   Zhentiw  阅读(737)  评论(0编辑  收藏  举报
编辑推荐:
· 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. 负载均衡和冗余技术
点击右上角即可分享
微信分享提示