1

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

Nigel
  • 23
  • 5
  • Really not sure what you are asking here... https://angular.io/api/common/NgClass. Have you looked at ngClass for assigning conditions to style html? – Darren Street Jun 19 '20 at 10:07
  • I don't understand exactly what you mean. Do you want to add a class based on the value passed into the set attribute from inside the directive? – Keff Jun 19 '20 at 11:07
  • @Keff Exactly ! Like in Javascript: element.classList.add("myclass-" + set), but from inside the directive. So that when no directive is present, there is no need for this class or ngClass – Nigel Jun 20 '20 at 12:17
  • 1
    I would suggest reading this post https://angular.io/guide/attribute-directives it explains how to get access to an ElementRef, then you can just use it as in Vanilla JS. – Keff Jun 22 '20 at 11:19

1 Answers1

1

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.

Keff
  • 989
  • 7
  • 27