繁体   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