首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角11 -将不同样式的图标添加到自定义按钮组件中

角11 -将不同样式的图标添加到自定义按钮组件中
EN

Stack Overflow用户
提问于 2021-01-11 15:00:33
回答 1查看 1K关注 0票数 4

在我的角11应用程序中,我实现了一个自定义按钮组件。对于样式设计,我使用TailwindCSS和TailwindUI。

按钮可以有多种颜色(redbluegray等),也可以有不同的大小(xssmmdlgxl)。

我想为这些按钮创建一个变体:一个带有前导图标的按钮,如下所示:https://tailwindui.com/components/application-ui/elements/buttons#component-8a4b7248253ad4c9ee892c655d7ff5ec

对于图标,我使用以下库:https://ng-heroicons.dimaslz.dev/

图标是一个组件,如:<mail-solid-icon></mail-solid-icon><bookmark-solid-icon></bookmark-solid-icon>等。

由于按钮的大小不同(xssmmdlgxl),我需要向图标添加自定义的Tailwind类。例如:

代码语言:javascript
复制
<app-button [size]="'xs'">
  <mail-solid-iconclass="-ml-0.5 mr-2" [size]="16"></mail-solid-icon>
  Button text
</app-button>

<app-button [size]="'xl'">
  <bookmark-solid-icon class="-ml-1 mr-3 h-5 w-5" [size]="20"></bookmark-solid-icon>
Button text

期望的结果:

我希望能够只提供图标组件,然后在按钮的组件类中添加类-ml-0.5 mr-2-ml-1 mr-3 h-5 w-5;以及size属性。

模板中使用的示例:

代码语言:javascript
复制
 <app-button [size]="'xl'">
  <bookmark-solid-icon></bookmark-solid-icon>
   Button text
 </app-button>

输出:

代码语言:javascript
复制
<app-button [size]="'xl'">
  <bookmark-solid-icon class="-ml-1 mr-3 h-5 w-5" [size]="20"></bookmark-solid-icon>
   Button text
 </app-button>

我尝试使用自定义指令并使用@ContentChild获取它,但我无法将类添加到其中。

谢谢!

Stackblitz示例:https://stackblitz.com/edit/angular-ivy-6gpcby?file=src%2Fapp%2Fbutton%2Fbutton.component.ts

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-14 09:23:58

这是一个示例代码,它可以帮助您实现您想要做的事情:https://stackblitz.com/edit/angular-ivy-xymefd?file=src%2Fapp%2Fbutton%2Fbutton.component.ts

我从您的代码中更改的内容是:

declarations.

  • Use

  • ButtonIconDirective添加到AppModule AppModule appButtonIcon,而不是将docsButtonIcon.

  • Inject ElementRef添加到ButtonIconDirective中。(我们将在ButtonComponent).

  • Append中使用ElementRef,一个模板变量到<bookmark-solid-icon>上,以获取其组件instance.

  • Rewrite ngAfterContentInit in ButtonComponent方法来更新size并在运行时添加新的CSS类:

)。

代码语言:javascript
复制
public ngAfterContentInit(): void {
  console.log( 'this.icon: ', !!this.icon);
  
  if (this.icon) {

    // reference to ng-heroicons component source code
    this.icon.style = '';
    this.icon.size = 50;     
    this.icon.renderStyle(); 

    this.renderer.addClass(this.iconi.er.nativeElement, '-ml-1');
    this.renderer.addClass(this.iconi.er.nativeElement, 'mr-3');
    this.renderer.addClass(this.iconi.er.nativeElement, 'h-5');
    this.renderer.addClass(this.iconi.er.nativeElement, 'w-5');      

    console.log(this.icon.style);
  }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65669268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档