代码之家  ›  专栏  ›  技术社区  ›  gjvatsalya

如何使用@ContentChildren并只呈现特定子组件而不是所有子组件?

  •  0
  • gjvatsalya  · 技术社区  · 7 年前

    我正在尝试创建一个通用的幻灯片组件,它将包含多个组件,然后它将基于某些用户操作循环。
    它非常类似于角材料 stepper component .

    到目前为止,我发现你可以 @ContentChildren 获取对多个(传入)组件/内容的引用,但我不确定如何实际呈现这些组件。

    下面是我创建的一个示例: https://stackblitz.com/edit/angular-yjfbwb
    app.component.html文件包含 <tours></tours> 标签,你可以把任何你想要的东西传进去,只要你用标签 #tour . 在tours.component.ts中,您会看到我只是在遍历传入的组件。
    但我该如何渲染它们呢?

    我在谷歌上搜索了一下,似乎不可能像我这样做?但也许我找得不对。理想情况下,我希望使这个旅游组件尽可能简单地用于我的团队(基本上是在上面的示例中是如何使用的)。

    任何帮助都将不胜感激!

    1 回复  |  直到 7 年前
        1
  •  2
  •   SplitterAlex    7 年前

    有很多方法可以做到这一点。

    这里有一个简单的解决方案。只是想知道。根据你的具体问题,你可能想换一种方式。

    对于您要在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

    推荐文章