如何解决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 举报,一经查实,本站将立刻删除。