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

标签 angular

我正在尝试创建一个通用的幻灯片组件,它将采用多个组件,然后它会根据特定的用户操作循环播放。
它与 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>;
}

Updated Stackblitz demo

关于angular - 我如何使用 @ContentChildren 并只呈现特定的子组件而不是所有子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51506636/

相关文章:

jquery - 访问 Angular 2 组件内的 JQuery 数据表

angular - 组件 "AppFooterComponent"的选择器应该用作元素

Angular 动画错误 - 减少没有初始值的空数组

Angular 2 GET 参数保持为空

html - 将参数传递给 Angular2 组件

angular - 如何在 Angular 中动态呈现 Markdown 文件?

javascript - 如何从 flatTreeNode 填充树?

angularjs - 字符串中的 Angular 2 绑定(bind)表达式(ng2-translate)

html - Angular 2 : create divs dynamically

Angular 6 + RxJs - concatMap 的错误处理