Angular 角度9-使用@ContentChildren

Angular 角度9-使用@ContentChildren,angular,typescript,Angular,Typescript,我有一个ButtonGroupComponent,需要在其中呈现两种类型的子级:ButtonActionComponent或ButtonNavigationComponent 我需要通过@ContentChildren来投射这些孩子,但是我能做什么,因为不可能 两个选择器都通过吗 @ContentChildren(??) public children: QueryList<??>; 其中ButtonActionComponent: 和按钮激活组件: 我是这样用的: @Cont

我有一个ButtonGroupComponent,需要在其中呈现两种类型的子级:ButtonActionComponent或ButtonNavigationComponent

我需要通过@ContentChildren来投射这些孩子,但是我能做什么,因为不可能 两个选择器都通过吗

@ContentChildren(??)
  public children: QueryList<??>;
其中ButtonActionComponent:

和按钮激活组件:

我是这样用的:

@ContentChildren(GroupableButton)
  public children: QueryList<GroupableButton>;

这一次的问题是,我无法将GroupableButton作为模块内的entryComponents传递。

您使解决方案过于复杂

为什么不简单地通过字符串选择器查询这两个组件:

@ContentChildren('templateRef1, templateRef2') allTypesOfButtons: QueryList<ButtonActionComponent | ButtonNavigationComponent>;
@ContentChildren('templateRef1,templateRef2')所有类型的按钮:QueryList;

我首先花时间在

上举了一个例子,而不是你现有的提供商,这样做:

providers: [{ provide: GroupableButton, useExisting: forwardRef(() => ButtonActionComponent) }],
这将确保您获得正确的组件,并可以根据您的需要循环组件

我不确定这是否解决了您的实例化问题,但您是否考虑过组件模板中良好的
ng content
标记,而不是手动实例化组件

<!-- put this where ever you want to project your buttons.... -->
<ng-content></ng-content>


她正在元素上循环。有了两个不同的查询列表,她就失去了顺序。@0xc14m1z你说的是什么顺序?OP没有提到任何orderWell,最后一个代码片段是反向数组上的
forEach
语句,因此,我假设需要一个特定的顺序,如果子元素列表必须以相反的顺序循环。。。但也许我错了@Elisa关于这一点,你能告诉我们什么?@0xc14m1z是的,你是对的,我需要保留按钮的确切顺序,因为我必须将它们放在子菜单中。如果顺序很重要,你可以为
ng content
中的每个按钮添加模板选择器,并像这样使用:
@ContentChildren('baseButton')children:QueryListStackblitz:顺便说一句,我认为这个问题可能与你的问题完全相同,你把问题复杂化了。你能退一步谈谈你的实际目标吗
@ContentChildren(GroupableButton)
  public children: QueryList<GroupableButton>;
...

this.children
  .toArray()
  .slice(0, visibleButtons)
  .reverse()
  .forEach((button) => {
    const factory = this.factoryResolver.resolveComponentFactory(
      GroupableButton
    );

    const component = this.visibleButtonsContainer.createComponent(
      factory,
      0,
      null,
      [[button.element.nativeElement]]
    );
    this.clonePropertiesFrom(button, component.instance);
    this.buttons.push(component);
  });

...
@ContentChildren('templateRef1, templateRef2') allTypesOfButtons: QueryList<ButtonActionComponent | ButtonNavigationComponent>;
providers: [{ provide: GroupableButton, useExisting: forwardRef(() => ButtonActionComponent) }],
<!-- put this where ever you want to project your buttons.... -->
<ng-content></ng-content>