DEV Community 👩‍💻👨‍💻

Pradip Khadka
Pradip Khadka

Posted on

Overwrite Portal Outlet

So, I have a custom portal outlet as such:
<div id="title-bar-outlet">some text content</div>

And I have a portal component like below:

import { CdkPortal, DomPortalOutlet } from '@angular/cdk/portal';
import {
  AfterViewInit,
  ApplicationRef,
  Component,
  ComponentFactoryResolver,
  Injector,
  OnDestroy,
  ViewChild
} from '@angular/core';

@Component({
  selector: 'app-title-bar',
  template: `
    <ng-template cdkPortal>
      <ng-content></ng-content>
    </ng-template>
  `
})
export class TitleBarComponent implements AfterViewInit, OnDestroy {
  @ViewChild(CdkPortal)
  private portal: CdkPortal;
  private host: DomPortalOutlet;

  constructor(
    private crf: ComponentFactoryResolver,
    private appRef: ApplicationRef,
    private injector: Injector
  ) {}

  ngAfterViewInit(): void {
    this.host = new DomPortalOutlet(
      document.querySelector('#title-bar-outlet'),
      this.crf,
      this.appRef,
      this.injector
    );
    this.host.attach(this.portal);
  }

  ngOnDestroy(): void {
    this.host.detach();
  }
}
Enter fullscreen mode Exit fullscreen mode

Now when using the portal like this:

<app-title-bar>Some title bar content</app-title-bar>
Enter fullscreen mode Exit fullscreen mode

I want the content in #title-bar-outlet to be replaced by content of app-title-bar component. However, above code just appends component contents to the #title-bar-outlet DOM element

Top comments (0)

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆