Currently, I am in the midst of developing a specialized component UI library for a specific project I'm involved in. This library will consist of unique stylized components with elements that are reused throughout.
As I work on this project, I find myself frequently toggling between the HTML template file and the style file, often duplicating styling code boilerplate (similar CSS properties with different values). It crossed my mind that I could revolutionize my approach to styling by introducing an Angular directive. This directive would either apply a predefined CSS class for consistent styling (such as input fields or buttons) or dynamically set the style of the component using the renderer for commonly used properties with varying values for specific components.
import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[SetWidth]'
})
export class SetWidthDirective implements OnInit {
@Input('SetWidth') width: number | string = 'auto';
@Input('Units') units?: 'px' | 'rem' | 'em' | '%';
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
let style = '';
if (typeof this.width == 'string') {
style = this.width;
} else {
let u = this.units || 'px';
style = `${this.width} ${u}`;
}
this.renderer.setStyle(this.el, 'width', style);
}
}
Usage example:
<div [SetWidth]="100" Units="rem">Hello World</div>
I've implemented similar directives for useful CSS styles like height, display, and template-grid-options. The customization provided by these directive classes has allowed me to streamline many repetitive styling declarations.
My main query revolves around whether utilizing this method is considered an anti-pattern or bad practice. My concern lies not in adhering to traditional styling practices, but rather in understanding the potential impact on performance, usability, and overall application efficiency. While this approach certainly enhances the developer experience, I wonder about its broader implications.