3

I have a simple directive and I would like to add a class to it :

@Directive({
  selector: '[appFieldLabel]',
})
export class FieldLabelDirective {
  @Input() tooltip: string;
  @Input() showOptional = true;

  @HostBinding('class.text-truncate')
  test = true;
}

this works, but I want it to always be set, is there a way without assigning an useless property like here test = true;

thank you

kian
  • 1,449
  • 2
  • 13
  • 21
Bobby
  • 4,372
  • 8
  • 47
  • 103
  • 2
    there are more options to do it https://stackoverflow.com/questions/39639098/using-a-directive-to-add-class-to-host-element – Kordrad Oct 19 '21 at 07:25

1 Answers1

3

Instead of prop = true you can just bind to class and then set value to a classes that you want, like this:

@Directive({
  selector: '[appFieldLabel]',
})
export class FieldLabelDirective {
  @Input() tooltip: string;
  @Input() showOptional = true;

  @HostBinding('class') private hostClass = 'text-truncate';
}

It's less useless, because you can modify classes via variable.

You could also bind class like this:

@Directive({
  selector: '[appFieldLabel]',
  host: {
    'class': 'text-truncate',
  }
})
export class FieldLabelDirective {
  // the rest of the code
}
Adrian Kokot
  • 2,172
  • 2
  • 5
  • 18