我正在尝试创建一个通用的幻灯片组件,它将采用多个组件,然后它会根据特定的用户操作循环播放。
它与 Angular Material 的 stepper component 非常相似.
到目前为止,我发现您可以使用 @ContentChildren
获取对多个(传入的)组件/内容的引用,但我不确定如何实际呈现组件。
这是我创建的示例:https://stackblitz.com/edit/angular-yjfbwb
app.component.html 文件包含一个 <tours></tours>
只要你用 #tour
标记它,你就可以传入任何你想要的标记。 .在 tours.component.ts 中,您会看到我只是循环遍历传入的组件。
但是我实际上如何渲染它们呢?
我用谷歌搜索了一下,似乎我的做法不太可能?但也许我没有正确搜索。理想情况下,我想让我的团队尽可能简单地使用这个旅游组件(基本上就是上面的例子)。
如有任何帮助,我们将不胜感激!
最佳答案
有很多方法可以实现这一目标。
这是一个简单的解决方案。只是为了得到这个想法。您可能希望根据具体问题采取不同的做法。
对于您想在游览组件中投影的每个元素,您都必须创建一个模板。您可以通过 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
浏览您的模板。
现在在你的 ToursComponent
里面注入(inject) 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>;
}
关于angular - 我如何使用 @ContentChildren 并只呈现特定的子组件而不是所有子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51506636/