Creating a custom dialog container using CdkDialogContainer

Viewed 19

I am writing an Angular (14.2.0) service to display a Tailwind/Flowbite dialog (modal in Flowbite language). It seems I must create a custom Angular CDK dialog container to maintain the DOM structure outline on the Flowbite page and to apply the classes correctly.

I don't know how to create and use such a container though, the CDK documentation is not particularly clear.

My service code looks like this:

import { Dialog } from '@angular/cdk/dialog';

@Injectable({
  providedIn: 'root'
})
export class FlowbiteService {

  constructor(public dialog: Dialog) {}

  openDialog<C>(component: ComponentType<C>) {
    return this.dialog.open(component, {
      backdropClass: 'dialog-backdrop',
      panelClass: 'dialog-panel',
      container: DialogContainerComponent
    });
  }

}

...and my DialogContainerComponent is very simple, looking like this (the CSS is not really important):

@Component({
  selector: 'app-dialog-container',
  templateUrl: './dialog-container.component.html',
  styleUrls: ['./dialog-container.component.css']
})
export class DialogContainerComponent extends CdkDialogContainer {
}

However, calling the service yields a app-dialog-container element, but it has no children in the DOM when rendered.

I thought perhaps the content would be projected, so I added <ng-content></ng-content> into the markup for DialogContainerComponent, but this has no effect.

How do I correctly create and use my custom CDK dialog container? The documentation gives no example really.

1 Answers

Ok, I decided to look through the source code and found that the template of the cdk-dialog-container contained this:

<ng-template cdkPortalOutlet></ng-template>

I put this is my own template and now it's working. Sorted.

Related