简体   繁体   中英

Not able to query Child Components Directive/Component form Parent using ViewChild

I am facing issue with querying a directive of the child component in a parent component Table component uses scrollableView directive. and table component is used in my Report summary component. in reportSummary component am trying to find the instance of scrollbaleView directive using @ViewChild. I was able to find the table component using @ViewChild(DataTable) table : DataTable; similarly, i should be able to find @ViewChild(ScrollableView) scrollview : ScrollableView; but it does not ViewChild documentation says this https://angular.io/api/core/ViewChild You can use ViewChild to get the first element or the directive matching the selector from the view DOM. If the view DOM changes and a new child matches the selector, the property will be updated. View queries are set before the ngAfterViewInit callback is called.

Interestingly table reference is not found in ngAfterViewInit function, i could get the value somewhere else. But scrollableView is not found at any point in time.

Expected behavior

scrollableView should also be queried and available.

Minimal reproduction of the problem with instructions

https://stackblitz.com/edit/child-directive-query

If you look at the template of the p-dataTable component you will see that the pScrollableView is only loaded to the DOM if the p-dataTable is scrollable .

datatable.ts

<ng-template [ngIf]="scrollable">

  <div class="ui-datatable-scrollable-wrapper ui-helper-clearfix">

    <div *ngIf="hasFrozenColumns()" [pScrollableView]="frozenColumns" frozen="true"
         [headerColumnGroup]="frozenHeaderColumnGroup" [footerColumnGroup]="frozenFooterColumnGroup"
         [ngStyle]="{'width':this.frozenWidth}" class="ui-datatable-scrollable-view ui-datatable-frozen-view">
    </div>
    ...
</ng-template>

So you have to define your DataTable so that it uses the ScrollableView, otherwise it will not be in the DOM.

<p-dataTable [value]="cars" [loading]="loading" [scrollable]="true" scrollHeight="100px" >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM