Is it deemed as an anti-pattern to establish directives for styling?

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.

Answer №1

Utilizing directives for styling similar components is not considered an anti-pattern; in fact, it enhances reusability and is seen as a best practice. However, if you only need to set the width of a component, it's recommended to use the built-in style directive.

In addition, instead of using an extra property for unit and checking the types of the width and unit passed, consider setting the type of the width property as a string and passing that into the setStyle function.

Furthermore, it might be beneficial to rename the SetWidth property to simply width.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hey there, I was wondering if it's possible to modify the color of the navbar when scrolling on a specific page

After the first 3 pages with a black background and a transparent navbar with white navigation items, I encounter visibility issues when scrolling to the colorful 4th page. Is there a way to change the navbar color on this specific page using ONLY HTML a ...

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

What is the best way to update just the image path in the source using jQuery?

I am currently working on implementing a dark mode function for my website, and I have successfully adjusted the divs and other elements. However, I am facing an issue with changing the paths of images. In order to enable dark mode, I have created two sep ...

Positioning items to align an image in the center with both left and right elements

There's a simple question I have for all you HTML and CSS experts out there. I'm attempting to center align a list next to an image, but I can't seem to figure out how to position the list to the left or right of the image. This is what my ...

How to Choose Between Landscape and Portrait Printing Modes in Firefox and Internet Explorer 8

Currently, I am using the latest version of FireFox and IE8. In order to change the printing orientation, I utilized the following code in my CSS file: @page { size: portrait; } You can find more information about the @page property here. Although it i ...

CSS slideshow animation is not functioning properly

Hey there, I'm new around here and I've got a question for you all. Please bear with me if I make any mistakes. So, I'm attempting to create a simple CSS slide image. In my animation code, I want the picture to fade from the left every time ...

Creating an intricate table layout using AngularJS and the ngRepeat directive

I'm attempting to create a table similar to the one shown in the image below using HTML5. In this table, there is a multi-dimensional matrix with Class A and Class B highlighted in yellow. Each class has three modes (highlighted in blue), and each mo ...

Icons that are clickable in ionic

I have successfully created a list card with 2 icons in each row. However, I am facing a challenge in making these icons clickable without disrupting the layout of the list. I attempted to add an ng-click to the icon element, but it did not work as expecte ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Unable to retrieve iFrame window due to an error

My challenge lies in obtaining the window of an iFrame using this particular code: var frameWindow = document.getElementById("loginframe"); var iWindow = frameWindow.contentWindow; However, I am consistently encountering this error message: Property ...

Leveraging the angular-in-memory-web-api in conjunction with Angular CLI

Encountering some frustrating issues while trying to integrate angular-in-memory-web-api into my Angular 2 project that was built using Angular CLI. Here's the current structure of dependencies inside my package.json: "dependencies": { "@angular/co ...

A perfectly organized and justified menu with evenly spaced horizontal list items

I couldn't find a solution to evenly spacing out a series of list items for a menu styled list. After realizing CSS alone wasn't enough, I decided to incorporate some javascript (jQuery). My goal was to have equal padding between each LI without ...

Adjusting the size of the background image without altering the background color

I am looking to create a background with a gradient color and an overlay background image. The image is simply a transparent icon, but I need to adjust its size without altering the overall background dimensions. Any assistance on this matter would be gre ...

Error in Angular ngFor loop: Type 'OrderItem' is not compatible with type 'Iterable<any>'

In my HTML code, I have the following structure: <div class="grid mb-5" *ngFor="let orderItem of order.orderItems"> <div class="col-2">{{ orderItem.product.name }}</div> <div class="col-2&qu ...

Tips for maximizing page layout efficiency without compromising on element visibility

What is occurring https://i.stack.imgur.com/Agjw6.gif The use of .hide() and .fadeIn(200) is resulting in a jittery effect that I would like to avoid. Desired Outcome When the user hovers over the menu icon, the menu icon should vanish the text "Pr ...

Issue with IE11: Flexbox with absolute positioning not sizing correctly, fills entire width instead of individual content

Here's a simple case to reproduce the issue: <div style="display: inline-block; position: relative; border: 1px solid black;"> short <div style="display: flex; position: absolute; border: 1px solid black; top: 100%; lef ...

Wait for the nested request to finish before returning the Observable

There are a pair of POST-requests within this function: function addArticle(request: IArticle) { const requestPath = `${this.backendUrl}/articles`; return this.http .post<IResponse<IArticleApiContract>>(requestPath, getArticleApiContra ...

Employ ion-grid for a layout reminiscent of Duolingo's design

I am exploring the idea of creating a layout similar to Duolingo's interface. I have an array that specifies which buttons should be displayed, and I want them to be organized in pairs, with any odd element centered within the layout. However, I am s ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

The partnership between Selenium and WhitePages has created an innovative solution

I am currently attempting to register on . The registration process requires entering my first name, last name, email address, and password. For the first name field, I attempted to locate the element by CSS using the syntax "input#name_fname", however, I ...