dzenesiz
dzenesiz

Reputation: 1542

Should I add class attributes to Angular component selector tags

I'd like to add class directly to selector in Angular 5. Something like this:

<myapp-selector class="myclass"></myapp-selector>

I've been searching for a while now, and I found some solutions like using host of @Component. But I can't find a definitive answer on the concrete question.

Is it safe and is it considered a bad practice?

Upvotes: 5

Views: 2979

Answers (2)

Pascal Precht
Pascal Precht

Reputation: 8893

I guess this depends really on what you're trying to achieve.

Simply adding a class to a component, is done by just adding it to the tag statically, just as you've already mentioned.

Adding a class conditionally can be done in multiple ways, one of which is using @HostBinding() or the component's host property

@Component({
  ...
})
class SomeComponent {

  @HostBinding('class.someClassName') shouldAddClass: boolean;

}

Or

@Component({
  host: {
    '[class.active]': 'somePropertyName'
  }
})
class SomeComponent {
  somePropertyName: boolean;
}

Now, the active class will be added when the property is true and remove when it's false.

Another alternative is using [ngClass] directive, which essentially does the same, just that the consumer of the component decides when class are being added and removed:

<some-component [ngClass]="{ active: somePropertyThatsEitherTrueOrFalse }">

Upvotes: 3

Pardeep Jain
Pardeep Jain

Reputation: 86750

The best approach would be apply stlye/class inside your component as container, But you can add classes to the component as well.

Upvotes: 4

Related Questions