Set an HTML class to host in an Angular directive

408 Views Asked by At

How would you do to add and set an HTML class that can be changed with a parameter, with an Angular directive ? Let's say we have a div with an already existing class, but no directive :

<div class="myClass"></div>

Now, we want to attach a directive to it, and one parameter :

<div directiveName set="X" class="myClass myClass-X"></div>

If I need a 4, then my class added dynamically would be changed like that :

<div directiveName set="4" class="myClass myClass-4"></div>

I totally know how to add a class with @hostbinding, but I can't find how to change this one dynamically with my "set" parameter

Thank you very much

1

There are 1 best solutions below

1
Keff On BEST ANSWER

If I understood your question correctly, this might be accomplished as follows:

I did this from memory, maybe something is not working as expected but I think you get the gist of it.

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[directiveName]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       
       // Check if element has the 'set' directive.
       if('set' in el.nativeElement.attributes){
         // Get the "set" attribute.
         const setAttribute = el.nativeElement.getAttribute('set');

         // Add the class to the element.
         el.nativeElement.classList.add(setAttribute);
       }
    }
}

"You use the ElementRef in the directive's constructor to inject a reference to the host DOM element, the element to which you applied 'directiveName'."

I would suggest checking this page out, it explains in quite a bit of detail how directives work.