有很多方法可以做到这一点。
这里有一个简单的解决方案。只是想知道。根据你的具体问题,你可能想换一种方式。
对于您要在tours组件中投影的每个元素,都必须创建一个模板。你可以通过
StructuralDirective
.
import {Directive, TemplateRef, Input} from '@angular/core';
@Directive({
selector: '[appTour]'
})
export class TourDirective {
@Input('appTour') id: number;
constructor(public template: TemplateRef<any>) {
}
}
标记您的内部元素
ToursComponent
使用指令(不要忘记星号):
<tours>
<p *appTour="123">hello</p>
<p *appTour="1234">world</p>
</tours>
要标识可以传递的指令,例如
id
到你的模板的旅游。
现在在你的内心
旅游组件
注入
TourDirective
通过
@ContentChildren
并将要呈现的模板传递到
ViewContainerRef | <ng-container>
import { Component, ContentChildren, QueryList } from '@angular/core';
import { TourDirective } from './tour.directive';
@Component({
selector: 'tours',
template: `
<ng-container *ngFor="let tour of tours.toArray()">
<ng-container *ngIf="tour.id === tourToDisplay">
<ng-container [ngTemplateOutlet]="tour.template"></ng-container>
</ng-container>
</ng-container>`,
})
export class ToursComponent {
public tourToDisplay = 123;
@ContentChildren(TourDirective) tours: QueryList<TourDirective>;
}
Updated Stackblitz demo