简体   繁体   中英

Using @ViewChild on a component inside a component getting undefined value

I'm using Primeng's Listbox and an ngx-bootstrap's dropdown components in my project. I used these components in my project in a way that the Listbox is inside the ngx dropdown.

<!--this is a ngx dropdown-->
<ul *dropdownMenu class="dropdown-menu" role="menu" >
     <div class="well well-dropdown">Customize Grid</div>

      <!-- this is a primeng listbox -->
         <p-listbox  #listbox [options]="persons"  [filter]="false" [(ngModel)]="selectedPerson" [multiple]="true" [checkbox]="true" [metaKeySelection]="false" [style]="{'max-height':'150px'}">               
         </p-listbox>

</ul>

I created a variable in the template (#listbox) so I can access it in my ts. So I was trying to perform @ViewChild but. I always getting undefined.

export class MyComponent implements OnInit, AfterViewInit{

 @ViewChild('listbox') mylist: Listbox;


 ngOnInit(){
   console.log(this.mylist);  // ==> getting undefined value
 }

 ngAfterViewInit(){
  console.log(this.mylist); // ==> still getting undefined value

 }
}

Take note that I already console it in NgAfterViewInit and still getting undefined value for the ViewChild.

For the purpose of testing, I tried moving the primeng's Listbox out of the ngx dropdown and it has a value. BUt when I try to place the listbox inside the ngxdropdown the the viewChild is undefined. As for my application needs I really need to place the listbox inside the ngx.

Add <!DOCTYPE html> to your template:

<!DOCTYPE html>
<!--this is a ngx dropdown-->
<ul *dropdownMenu class="dropdown-menu" role="menu" >
     <div class="well well-dropdown">Customize Grid</div>

      <!-- this is a primeng listbox -->
         <p-listbox  #listbox [options]="persons"  [filter]="false" [(ngModel)]="selectedPerson" [multiple]="true" [checkbox]="true" [metaKeySelection]="false" [style]="{'max-height':'150px'}">               
         </p-listbox>

</ul>

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