使用自定义CSS类创建组件

huangapple go评论69阅读模式
英文:

createComponent with custom CSS class

问题

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

我有一个用于加载独立组件的工作函数(Angular 15)。
我想要动态地向我的 viewContainer 添加一个 CSS 类,例如 class='fade'。基本上,我希望在创建后让 AlbumComponent 淡入显示。对我来说,不能在 AlbumComponent 中添加 class 'fade' 不是一个选项。
有人可以提供帮助吗?谢谢。

英文:
   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.

答案1

得分: 0

viewContainerRef.createComponent方法返回ComponentRef<C>实例,该实例通过location属性引用组件的宿主。

所以这是你的谜题:

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');
}
英文:

viewContainerRef.createComponent method returns ComponentRef<C> instance

which contains reference to component's host through location property

So here's your puzzle:

async getAlbum() {
  const { AlbumComponent } = await import(&quot;src/app/album/album.component&quot;);
  // this.viewContainer.createComponent(AlbumComponent);
  const componentRef = this.viewContainer.createComponent(AlbumComponent);
  componentRef.location.nativeElement.classList.add(&#39;fade&#39;, &#39;show&#39;);
}

huangapple
  • 本文由 发表于 2023年1月9日 09:56:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定