Search code examples
javascriptangularangular-cdk

@ViewChild(CdkPortalOutlet) returns undefined in AfterViewInit


Trying to query a ng-template with CdkPortalOutlet is always unsuccessful, and I cant understand why?

<ng-template CdkPortalOutlet></ng-template>

@ViewChild(CdkPortalOutlet) test: CdkPortalOutlet;

stackblitz


Solution

  • In order to use CdkPortalOutlet directive in AppComponent template you have import PortalModule in AppModule(i.e. NgModule where AppComponent has been declared)

    import { PortalModule } from '@angular/cdk/portal';
    ...
    
    @NgModule({
      imports:      [ BrowserModule, FormsModule, PortalModule, OverlayModule ],
                                                  ^^^^^^^^^^^^
      declarations: [ AppComponent ],
      bootstrap:    [ AppComponent ]
    })
    
    export class AppModule { }
    

    Also the Angular HTML parser is case sensitive so that you need to use it like:

    <ng-template cdkPortalOutlet></ng-template>
                 ^^^
              lower case
    

    Forked Stackblitz