1

我在页面的左侧并根据选择的 p-tree 节点在右侧调用相应的表数据。我只能在用户选择 p-tree 节点时显示表格,因此在页面加载右侧侧面板是空的。有什么方法可以在 component.ts 文件的 ngOnInit() 中触发 (onNodeSelected) 吗?

这是我尝试使用 viewchild 概念的方法

<div> 
<p-tree #myDiv  [value]="files" selectionMode="single" [(selection)]="selectedFiles" (onNodeSelect)="nodeSelect($event)" (onNodeExpand)="expandNode($event)"></p-tree>
</div>

组件.ts

ngOnInit(){
let el: HTMLElement = this.myDiv.nativeElement;
console.log(el);  // cannot read property 'nativeelement' of undefined
}
4

1 回答 1

0

您必须为您的元素添加 {static: true} 以使其在 ngOnInit 中可用

@ViewChild(myDiv, { static: true })myDiv: ElementRef;

否则您可以访问ngAfterViewInit 中的 @ViewChild 元素ngAfterContentInit 中的 @ContentChild

这是 Angular 8+ 的更改

于 2021-11-03T12:00:34.810 回答