簡體   English   中英

Angular - 如何在 ng-container ngTemplateOutlet 中插入兩個組件?

[英]Angular - How to insert two components inside a ng-container ngTemplateOutlet?

我創建了一個名為 wrapperComponent 的包裝器組件:

export class Wrappercomponent {
  @ContentChild(TemplateRef) detailRef;

  toggleComponents: boolean = false;
  constructor() {}
  toggle() {
    this.toggleComponents = !this.toggleComponents;
  }
}

我有這個模板 html:

<div *ngIf="toggleComponents; else plugintemplate">
  <ng-container *ngTemplateOutlet="detailRef"></ng-container>
</div>
<ng-template #plugintemplate></ng-template>
<button (click)="toggle()">Toggle</button>

我想在包裝器組件(my-component-1 和 my-component-2)中切換兩個組件:

<wrapper-component>
  <ng-template #detailRef>
    <my-component-1></my-component-1>
  </ng-template>
  <my-component-2></my-component-2>
<wrapper-component>

根據我的邏輯,我只能看到插入到 templateRef detailRef 中的組件,但另一個組件 (my-component-2) 永遠不可見。 如何在兩個不同的容器中插入兩個組件?

此行將始終只是 select 第一個TemplateRef

@ContentChild(TemplateRef) detailRef;

您可以為兩個模板提供唯一標識符:

<wrapper-component>
  <ng-template #detailRef>
    <my-component-1></my-component-1>
  </ng-template>
  <ng-template #pluginRef>
    <my-component-2></my-component-2>
  </ng-template>
</wrapper-component>

然后 select 他們使用字符串

export class WrapperComponent {
  @ContentChild("detailRef") detailRef;
  @ContentChild("pluginRef") pluginRef;
  toggleComponents: boolean = false;

  toggle() {
    this.toggleComponents = !this.toggleComponents;
  }
}

一個簡單的三元語句就足以切換它們

<ng-container *ngTemplateOutlet="toggleComponents ? detailRef : pluginRef"></ng-container>
<button (click)="toggle()">Toggle</button>

Stackblitz: https://stackblitz.com/edit/angular-ivy-vyuv3x?file=src/app/wrapper/wrapper.component.ts

ContentChild 文檔: https://angular.io/api/core/ContentChild


您還可以使用@ContentChildren(TemplateRef)獲取所有內部模板,無需標識符。 在這個例子中,我只是循環任意數量:

<wrapper-component>
  <ng-template>
    <my-component-1></my-component-1>
  </ng-template>
  <ng-template>
    <my-component-2></my-component-2>
  </ng-template>
  <ng-template>
    <my-component-3></my-component-3>
  </ng-template>
</wrapper-component>
export class WrapperComponent {
  @ContentChildren(TemplateRef) templates: QueryList<TemplateRef<any>>;
  index = 0;

  get currentTemplate() {
    return this.templates.get(this.index);
  }

  cycle() {
    this.index = (this.index + 1) % this.templates.length;
  }
}
<ng-container *ngTemplateOutlet="currentTemplate"></ng-container>
<button (click)="cycle()">Cycle</button>

Stackblitz: https://stackblitz.com/edit/angular-ivy-rzyn64?file=src/app/wrapper/wrapper.component.ts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM