Angular语言 - 如何在一个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)永远不可见。如何在两个不同的容器中插入两个组件?

这一行将始终只选择第一个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>

然后使用字符串

选择它们
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 docs: 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

最新更新