Angular ViewChildren 返回 undefined

问题描述

关于与此 Angular 功能相关的 SO,我已经解决了很多其他问题,但似乎没有任何解决方案对我的场景有帮助。我正在使用 Angular Material tree component,并尝试在完全展开的节点内生成一个组件。

我的Tree.component.html

<ng-container class="tree-content">
    <mat-card>
        <mat-tree [dataSource]="dataSource" [treeControl]="treeControl">
            <mat-tree-node *matTreeNodeDef="let node; when: hasChild" matTreeNodePadding>
                <ng-container *ngIf="node.expandable">
                    <button mat-icon-button matTreeNodetoggle [attr.aria-label]="'Toggle ' + node.name" (click)="generateTreeContent(node,treeControl.isExpanded(node))">
                        <mat-icon class="dark">
                        {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
                        </mat-icon>
                    </button>
                    <p>{{node.name}}</p>
                </ng-container>
                <app-dynamic></app-dynamic>
            </mat-tree-node>
        </mat-tree>
    </mat-card>
</ng-container>

我在 ViewChildren 中的 Tree.component.ts 装饰器声明:

@ViewChildren(DynamicComponent) children: QueryList<DynamicComponent>;

我的Dynamic.component.ts

@Component({
    selector: 'app-dynamic',templateUrl: './Dynamic.component.html',styleUrls: ['./Dynamic.component.scss']
})
export class DynamicComponent implements OnInit,AfterViewChecked {
    constructor(public componentFactoryResolver: ComponentFactoryResolver,public viewContainerRef: ViewContainerRef,public changeDetectorRef: ChangeDetectorRef,public ref: ElementRef) {
    }
    ...
}

每次我尝试访问 children 时,QueryList 都不会产生任何结果。

我尝试过的其他事情:

  • 使用“读取”元数据属性

    *.ts

    @ViewChildren('dynamic',{ read: DynamicComponent }) children: QueryList<DynamicComponent>;
    

    *.html

    <app-dynamic #dynamic></app-dynamic>
    
  • 通过 QueryList 订阅 AfterViewInit() 更改:

    public ngAfterViewInit(): void { 
        this.children.changes.subscribe((c: QueryList<DynamicComponent>) =>
        {
          ...
        });
    }
    
  • 使用 ContentChildren(带和不带 'read' 参数):

    *.ts

    @ContentChildren('dynamic',{ read: DynamicComponent }) children: QueryList<DynamicComponent>;
    

    *.html

    <app-dynamic #dynamic></app-dynamic>
    
  • 通过指令访问组件:

    @ViewChildren('dynamic',{ read: DynamicDirective }) children: QueryList<DynamicDirective>;
    
  • 强制变更检测后访问:

    this.viewContainerRef.detectChanges();
    console.log(this.children.toArray());
    

在这里做错了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)