javascript - Angular 11 - 将不同样式的图标添加到自定义按钮组件
问题描述
在我的 Angular 11 应用程序中,我实现了一个自定义按钮组件。对于样式,我使用 TailwindCSS 和 TailwindUI。
按钮可以有多种颜色(red
、blue
、gray
等),也可以有不同的尺寸(xs
、sm
、md
、lg
、xl
)。
我想为这些按钮创建一个变体:一个带有前导图标的按钮,如下所示: 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>
。
由于按钮的大小不同(xs
、sm
、md
、lg
、xl
),我需要为图标添加自定义 Tailwind 类。例如:
<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
财产。
模板中的使用示例:
<app-button [size]="'xl'">
<bookmark-solid-icon></bookmark-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
</app-button>
我尝试使用自定义指令并使用它来获取它@ContentChild
,但我无法向其中添加类。
谢谢!
Stackblitz 示例: https ://stackblitz.com/edit/angular-ivy-6gpcby?file=src%2Fapp%2Fbutton%2Fbutton.component.ts
解决方案
这是可以帮助您实现您想要做的事情的示例代码:https ://stackblitz.com/edit/angular-ivy-xymefd?file=src%2Fapp%2Fbutton%2Fbutton.component.ts
我对您的代码所做的更改是:
- 添加
ButtonIconDirective
到 AppModule 声明。 - 使用
appButtonIcon
而不是docsButtonIcon
. - 注入.
ElementRef
_ButtonIconDirective
(我们将在 中使用 ElementRefButtonComponent
)。 - 将模板变量附加到
<bookmark-solid-icon>
以获取其组件实例。 - 重写方法以
ngAfterContentInit
在运行时ButtonComponent
更新size
和添加新的 CSS 类:
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);
}
}
推荐阅读
- java - 得墨忒耳定律不适用于这种情况?
- java - Datatables数据错误地附加到表中
- python - 简单的海龟命令将海龟图形窗口带到前台?(OS X El Capitan 上的 python 3)
- ios - 在 UIView 和 UIViewController 之间传递数据
- c - 在 C 中交换动态分配的变量时,临时变量是否需要 free?
- spring-boot - Spring Security 在 Authentication 上获取延迟加载的属性
- excel - Excel Vba字典未循环
- android - 尝试选择图像时未能提供结果 ResultInfo
- javascript - 在 chrome 扩展中,如何使用内容脚本注入 Vue 页面
- node.js - 更新部署 - 重新部署到谷歌云后上传的图像被删除