Home > OS >  createComponent with custom CSS class
createComponent with custom CSS class

Time:01-10

   async getAlbum() {
    const { AlbumComponent } = await import("./album/album.component");
    this.viewContainer.createComponent(AlbumComponent);
  }

I do have a working function to load a standalone component (Angular 15). I would like to add a CSS class dynamically to my viewContainer - for example class='fade'. Basically, I would like to have the AlbumComponent fade in after it has been created. to add class 'fade' in the AlbumComponent is NOT an option for me. Anyone? Thanks.

CodePudding user response:

viewContainerRef.createComponent method returns ComponentRef instance

which contains reference to component's host through location property

So here's your puzzle:

async getAlbum() {
  const { AlbumComponent } = await import("src/app/album/album.component");
  // this.viewContainer.createComponent(AlbumComponent);
  const componentRef = this.viewContainer.createComponent(AlbumComponent);
  componentRef.location.nativeElement.classList.add('fade', 'show');
}
  • Related