【问题标题】:Angular 6: get reference to Components created with *ngFor inside ng-container tagAngular 6:获取对在 ng-container 标记内使用 *ngFor 创建的组件的引用
【发布时间】:2019-02-18 02:20:49
【问题描述】:

我正在使用 ng-container 迭代列表并创建组件

    <ng-container *ngFor="let f of optionsList; let i = index;">

                <!-- component-->
                <app-component  #fieldcmp  *ngIf="isAppComponent(f)" ></app-field>


                <!--another components-->
                <app-anoter-component1 *ngIf="isAnotherComponent1(f)"> </app-anoter-component1>
...
                <app-anoter-componentn *ngIf="isAnotherComponentn(f)"> </app-anoter-componentn>

            </ng-container>

我会列出 ng-container 中的 References 组件。

我尝试使用 @ViewChildren('#fieldcmp') 字段列表:查询列表;和 @ContentChildren('#fieldcmp') 字段列表:查询列表; 在父组件内部,但如果我尝试在 ngafterViewInit 中访问,我没有得到任何元素

ngAfterViewInit() {
        this.fieldsList.forEach((child) => {  /* some logic....*/});
    }

有人可以帮助我吗? 谢谢

-----------更新 -----------

使用@ViewChildren('fieldcmp') 修复后,我有一个ElementRef 列表,而不是我的AppComponent。 我投了它,所有的工作

this.filedsList 
            .forEach((child) => { atLeastOneRequired = atLeastOneRequired || (<ReusableFieldComponent> child).isRequired();
    });

谢谢你的帮助

【问题讨论】:

  • 我认为应该只是@ViewChildren('fieldcmp')(没有#符号,只在模板中使用)

标签: angular angular6 ngfor viewchild ng-container


【解决方案1】:

只需从 ViewChildren 选择器中删除 # 符号 - 仅在模板中使用:

@ViewChildren('fieldcmp') fieldsList: QueryList;

或者你可以使用组件类作为选择器:

@ViewChildren(HelloComponent) fieldsList: QueryList<HelloComponent>;

在这里工作堆栈闪电战:https://stackblitz.com/edit/angular-xeudlp

【讨论】:

  • 使用@ViewChildren('fieldcmp') 修复后,我有一个ElementRef 列表,而不是我的AppComponent。如何转换或转换为我的组件类型?
  • 使用其他方式获取组件实例(使用@ViewChildren(HelloComponent)
  • with @ViewChildren(HelloComponent) 我有 lenght = 0。我认为问题在于组件位于 内。对于这个存在 @ContentChildren 但替换为 ViewChildren 我也没有参考。
  • 它对我有用,请参阅我提供的 stackblitz 示例。我还将容器元素更改为 ng-container 并且仍然按预期工作。
  • 我使用铸造,它的工作。感谢您花费的时间
【解决方案2】:

尝试创建并清空directive,然后查询您的指令并阅读ElementRef

@ViewChildren(MyDirective, {read: Element Ref}) Kids: QueryList<ElementRef>;

我面前没有我的电脑,但这就是我的想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2023-03-30
    • 2019-01-14
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多