0

I am using @HostBinding('class') to inject classes into the host element. The classes to be injected are generated based on user-supplied parameters. The problem I ran into and I could not find anyone else experiencing is that the classes are applied in an order different from the way I expected them.

For example, having a component defined below:

import {Component, HostBinding, Input} from '@angular/core';

@Component({
  selector: '[icon]',
  template: `
    <ng-content></ng-content>
  `
})
export class SuiIconComponent {
  @Input() iconType = '';

  @HostBinding('class')
  get classes(): string {
    return [this.iconType, 'icon'].join((' '));
  }
}

When I apply the component like shown below:

<div icon iconType="car"></div>

And inspect, I see <div class="icon car"></div> instead of the appropriately formatted <div class="car icon"></div>. I have tried reversing the array before joining but that did not help either. Is there any way I get the classes to get rendered in the proper order?

Edit: I realized the classes are being rearranged in alphabetic order.

1 Answers1

0

I'm not sure why angular changes the order, but you can solve your problem with little bit of change in your template.

@Component({
  selector: 'icon',
  template: `
    <div [ngClass]="iconType + ' icon'">
       <ng-content></ng-content>
    </div>
  `
})
export class SuiIconComponent {
  @Input() iconType = '';
}

and use it as follows

<icon iconType="car">
   Some content here
</icon>
Bunyamin Coskuner
  • 8,719
  • 1
  • 28
  • 48
  • I do not want to create a component as such, I want my component to modify what the user has and give them the leeway to make further changes as they see fit instead of giving them a backed component – Bolorunduro Winner-Timothy May 11 '20 at 15:47
  • You already created a component and used it as directive. In my case, you would use it as element and nothing would change – Bunyamin Coskuner May 11 '20 at 15:48