Angular ContentChildren(Component) 获取任何类型

问题描述 投票:0回答:3

我知道您可以通过指定特定的组件类型来获取子组件

@ContentChildren(SpecificComponent)
但我可以使用
@ContentChildren(SOMETHING)
并获取一个组件而不管其类型,就像通用组件一样吗?

angular angular5 angular6
3个回答
5
投票

不确定为什么有人不说原因就否决了这个但最终找到了解决方案:

@ContentChildren('childComponent') childComponents;

我将字符串而不是组件传递给内容子项。该字符串允许我使用参考选择器(#childComponent)


2
投票
@Component({
  template: '<ng-content></ng-content>',
})
export class TestComponent implements AfterContentInit {

    constructor(private readonly elementRef: ElementRef) {
    }

    ngAfterContentInit() {
        const element = this.elementRef.nativeElement as HTMLElement;
        // do wathever you want with element.children
    }
}

0
投票

如果我需要为子列表执行此操作,我总是创建一个指令:

@Directive({ 
    selector: '[childComponent]',
    standalone: true
})
export class GenericChildDirective { }

然后在组件中:

@ContentChildren(GenericChildDirective) children!: QueryList<GenericChildDirective>;

实际上我认为没有办法按照最初的要求做到这一点。

注:这个和Angular例子基本一样https://angular.io/api/core/ContentChildren#tab-pane-example

© www.soinside.com 2019 - 2024. All rights reserved.