Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a class to directive in angular

Tags:

class

angular

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

like image 360
Crocsx Avatar asked Feb 22 '26 05:02

Crocsx


1 Answers

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
}
like image 126
Adrian Kokot Avatar answered Feb 24 '26 20:02

Adrian Kokot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!