显示标题字符串/ templateRef Angular

问题描述 投票:2回答:2

我试图改善代码而不是附加条件,所以我决定创建一个指令或可能的话,它可以帮助我根据选项卡的类型(字符串或templateRef)打印选项卡的标题,我的代码是在下面的代码中,我的Tabs / Tab组件中使用了此代码,而Stepper / step组件中也使用了此代码,因此,我相信创建可重用的代码会很棒。我尝试用ElementRef,Renderer2,ViewContainerRef,TemplateRef ...来做,但是我没有成功。

<ng-container *ngIf="tab.isLabelTemplate">
     <ng-container *ngTemplateOutlet="tab.title">
     </ng-container>
</ng-container>
<ng-container *ngIf="!tab.isLabelTemplate">{{ tab.title }}</ng-container>

isLabelTemplate看起来像这样:

get isLabelTemplate(): boolean {
  return this.title instanceof TemplateRef;
}

非常感谢:)

angular angular-directive angular-components angular-pipe angular-renderer2
2个回答
1
投票

您可以利用Angular低层API动态地操作DOM的结构:


0
投票

或者您也可以将此逻辑移至“帮助器”组件,然后在TabComponent中使用它。因此,此逻辑位于单个位置(DRY)。帮助器组件(TitleComponent)与您在TabComponent中使用的组件相同。这样,您只需移动“问题”,而不必一次又一次地重复。而且仍然很容易阅读。

© www.soinside.com 2019 - 2024. All rights reserved.