5
votes

Angular 2: When to use attribute directives and when to use component styles?

There are 2 main ways to style an element in Angular 2 described in the official Angular 2 Docs.

  • Attribute Directives
  • Component Styles

Component styles can be implementated in these ways: (Template Inline Styles, Style URLs in Metadata, Template Link Tags, CSS @imports)

I'm interested in which ways to use to apply styles to elements, when.

Since they're all mentioned in the official docs, each of them may be best to use in certain circumstances (even template inline styles in some circumstances??)?

The docs demo attribute directives are responding to user events. They demo component styles without events.

Does this mean that in most circumstances, it is good practice to use attribute directives when styling is applied in response to events, and component styles when styling is applied without events?

2

2 Answers

4
votes

Another hint from the official angular 2 style guide that I just found:

style 06-01

Do use attribute directives when you have presentation logic without a template.

The only reason I can think of to have presentation logic without a template is to make it usable in more than one component.

We could easily define a global css style with :hover and use it in one to many templates. That is also

presentation logic without a template

The difference in usage is:

<div tohHighlight>Bombasta</div> vs <div class="tohHighlight">Bombasta</div>

I can't really see a benefit to one over the other but the Angular 2 official docs always demo attribute directives with an event, and for any styling that doesn't involve an event, they use css.

In this example in style 06-01, it is yet again, in an event (mouseover).

So I think they believe it's best to use attribute directives when an event is involved.

I'm just learning Angular 2 so am not sure on the pros and cons of each method of styling, but here are some possible ones I can think of:

Possible benefits of attribute directives over css

  • The selector is probably more fool-proof than a global css selector (global css selectors can become messy and not select the element intended if done incorrectly).
  • (I think) you import attribute directives into the component which demonstrates the intention to use it (readability).
  • An attribute directive is not global, you have to import it to use it.

Possible cons of attribute directives over css

  • However, an attribute directive is a little bit more code and possibly a separate file to be best practice, so it may be a bit more "heavy".
1
votes