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

Overlapping Dropdown Javascript Menus

To achieve the desired effect in the header, I need to create two expandable dropdown menus for the first two titles. My coding experience is limited, especially when it comes to javascript and jquery. Currently, I have managed to create the effect for one ...

Adding CSS stylesheets on-the-fly in JavaFX

I am looking to incorporate a CSS file from the filesystem into my application. The goal is to allow users to dynamically add JavaFX CSS files that can be created by anyone and stored anywhere on their system. I attempted a test scenario to see if adding ...

Creating CSS Effects for Text Hover and Transition

Looking for help to implement the hover effect 4 on the following site: . I was able to create a test on JSFiddle, check it out here: https://jsfiddle.net/34aaqh70/ Struggling to make it auto-responsive, any tips would be appreciated. If there's a ...

My Jquery "animate" is only triggered once instead of on each function call. What could be causing this issue?

I have set my navigation to dock at a specific document height on the top of the viewport, and when it docks, it should display a dropdown animation. $(document).scroll(function(){ var x = $(window).scrollTop(); if(x>=700){ $("header ...

Avoid wrapping elements

Is there a foolproof method or best practice to prevent an HTMLElement from wrapping? Specifically, I'm referring to elements with relative positioning. One possible solution could be using absolute elements and adjusting their left position based on ...

Whenever I open my collapsible dropdown, it seems to leap up unexpectedly

When I interact with the collapsible card, it has a jerky animation. I would like it to open smoothly instead. The issue lies with the tooltip-cus class. If I remove position: relative;, the opening animation is smooth, but then the position of the toolti ...

Utilizing SASS to retrieve the H, S, L values from a color

Is there a way to extract the H, S, L values from a hex color in SASS and assign them to separate CSS variables? $colors: ( "primary": $primary, "secondary": $secondary) !default; :root { @each $color, $value in $colors { -- ...

Issue with Highcharts: Y-axis values are not being bound correctly

Having trouble binding certain values to the Y axis of a highchart. The first value from the array displays correctly, but the rest are showing up incorrectly. chartOptionsLine: any = { yAxis: { categories: ['1 ms', '5 ms', ...

React Hamburger Menu not working as intended

I am facing an issue with my responsive hamburger menu. It is not functioning correctly when clicked on. The menu should display the navigation links and switch icons upon clicking, but it does neither. When I remove the line "{open && NavLink ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Filtering an observable using criteria from another source

I'm currently facing a challenge where I need to map observables by filtering them based on events emitted from other observables. The main question at hand is: Is there a way to pass a property of an event to a filter function? In the following exa ...

The attribute 'pixiOverlay' is not found in the property

Working on my Angular 8 project, I needed to display several markers on a map, so I chose to utilize Leaflet. Since there were potentially thousands of markers involved, I opted for Leaflet.PixiOverlay to ensure smooth performance. After installing and imp ...

The dropdown menu is being truncated

I am having an issue with a drop-down menu being cut off by its parent div. When I increase the height of the parent div, the drop-down menu becomes visible. Can someone please assist me? Below is my code snippet: MarkUp <div id="main-navigation" clas ...

jQuery menu fails to toggle the class name

The toggle functionality in the Menu is not working properly. Upon clicking the toggle button, I encountered the following JavaScript error: "message": "Uncaught TypeError: Cannot read property 'toggle' of undefined", "filename": "https://st ...

What is the name of the scrolling header effect achieved in the following?

I've been seeing a lot of people using a unique header effect lately and I'm curious to learn more about how it's done. Can anyone explain the process behind achieving this effect, what it's called, and if there are any good tutorials a ...

Encountering spacing problems on IE9 and FF11 while using OS X

After conducting some testing on a design I coded, I found that it functions well in FF 13, Chrome 21, IE 7/8, and Opera 11.62 for Windows, as well as Safari 5.1 for OS X. Unfortunately, since I only have WinXP, I had to utilize Adobe Browserlab to test f ...

MDL Tab loading Problem

When visiting my website at this link, which is powered by MDL from Google, there is a troublesome issue that occurs. The #harule tab briefly appears before disappearing. This tab should actually be hidden on the page until a user clicks on the harule tab ...

Position icons and images on the right side, and the textarea on the left side of the page (using Twitter

Summary: Here is the desired end result shown in the image below. Alternatively, you can refer to the JSFiddle. Ideally, only CSS should be used without changing the DOM structure. The icons need to be aligned completely to the right using the .pull-right ...

Having trouble getting the CSS footer from cssstickyfooter.com to function properly

I tried implementing some basic CSS from to create a sticky footer that remains at the bottom of the page regardless of content length. However, I am encountering a problem with the footer not behaving as expected. There are actually two issues with the f ...

Sending Multiple Data from Multiple Rows in Angular

I am struggling to figure out how to submit an array of data when clicking on multiple rows in Angular. Specifically, I am confused about adding rows and submitting data from those newly added rows. I have been utilizing (ngSubmit) for the submission pro ...