Home > Blockchain >  Add a class to directive in angular
Add a class to directive in angular

Time:10-20

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

CodePudding user response:

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
}
  • Related