How to get ViewChild from content inside the cdkPortal

Viewed 592

I have several components that bring "tools" with them and on creation insert those tools into predefined "named" places in the app, like left/right/side toolbars. They do it with Angular CDK Portals. It looks like this:

// component template here...

// then portions of UI for portals, like this:
<ng-template cdkPortal #leftToolbar>
    <app-search-input #search (search)="onSearch($event)"></app-search-input>
</ng-template>

My goal is to somehow get the reference to app-search-input component placed inside the portal.

Shown below doesn't work, this.searchEl is always undefined:

// component class
@ViewChild('search', {static: true}) searchEl: SearchInputComponent;

Any thoughts, guys?

1 Answers

You're not able to access to any content from ng-template till it has been rendered.

But you can always subscribe to the event when your ViewChild is being initialized through setter:

@ViewChild('search') set searchEl(value: any) {
  if (value) {
    // do smth
  }
};

Stackblitz Example

Related