// Tutorial //

All the Ways to Add CSS to Angular 2 Components

Draft updated on Invalid Date
Default avatar
By Chris Nwamba
Developer and author at DigitalOcean.
All the Ways to Add CSS to Angular 2 Components

This tutorial is out of date and no longer maintained.

Introduction

Writing styles for large applications can be a really challenging task as styles get easily mixed up and confusing. The major issue is usually encountered when trying to structure your styles and give proper naming of individual styles.

With time, patterns were introduced to enhance style organization and most of these patterns are implemented when we make use of pre-processors like Sass and Less. The significant thing about these patterns is that they suggest organizing our styles and templates in the form of COMPONENTS.

Angular 2 is component-based which means that every UI functionality is built as a component. Therefore, as component-based styling is a recommended pattern, Angular 2 is just about to make writing styles a rather enjoyable experience. We will discuss different styling techniques and how to use them, but before that, we need to understand the concept of Shadow DOM and View Encapsulation.

Shadow DOM and View Encapsulation

Shadow DOM is included in the Web Components standard by W3C. Shadow DOM basically allows a group of DOM implementations to be hidden inside a single element (which is the basic idea of components) and encapsulate styles to the element. This means that encapsulated styles will only be available for that group of DOM elements and nothing more.

Abstraction with Shadow DOM

Remember that the idea of web components and shadow DOM is relatively new and not all browsers can handle the concept. This is where one of the major advantages of Angular 2 comes in as it allows us to choose whether to implement Shadow DOM, just emulate it (default), or not use it at all. This technique of handling Shadow DOM in Angular 2 is known as View Encapsulation.

The 3 states of view encapsulation are:

  • None: All elements are spit out - no Shadow DOM at all.
  • Emulated: This actually tries to emulate Shadow DOM to give us the feeling that we are scoping our styles. This is not a real Shadow DOM but a strategy to make all browsers smile at our code.
  • Native: This is the real deal as shadow DOM is completely enabled.

Setting encapsulation is quite simple and is done right inside the @component decorator:

@Component({
  templateUrl: 'card.html',
  styles: [`
    .card {
      height: 70px;
      width: 100px;
    }
  `],
  encapsulation: ViewEncapsulation.Native
  // encapsulation: ViewEncapsulation.None
  // encapsulation: ViewEncapsulation.Emulated is default
})

Styling Techniques

Now that we have taken some time to put Shadow DOM and View Encapsulation straight, we can go ahead to understand the different techniques of styling an Angular component. Cards are common components that we are familiar with, so permit me to use them for the illustrations.

Component Inline Styles

This technique is the most obvious styling technique in Angular 2. This is because it is recommended, makes sense with the concept of components in mind and found everywhere in the Angular 2 documentation. It is implemented in the @Component decorator of our component class like so:

@Component({
  templateUrl: 'card.html',
  styles: [`
    .card {
      height: 70px;
      width: 100px;
    }
  `],
})

The expected behavior in various view encapsulation techniques are:

  • None: The style is wrapped in a style tag and pushed to the head.
  • Emulated: The style is wrapped in a style tag, pushed to head, and uniquely identified so it can be matched with its component’s template. With that, the styles will be used for only the template in the same component.
  • Native: Behaves as expected of web components.

External Stylesheets

Just like our everyday method of including styles from external styles which have an extension of .css, we could also import external styles in an Angular 2 component. It is as simple as importing templates with the templateUrl property in @Component decorator.

@Component({
  styleUrls: ['css/style.css'],
  templateUrl: 'card.html',
})

The expected behavior in various view encapsulation techniques are:

  • None: The style is wrapped in a style tag and pushed to the head. It is appended right after the component inline style.
  • Emulated: The style is wrapped in style tag, pushed to head, and uniquely identified so it can be matched with its component’s template just like the component inline style. As you can see, you must have guessed wrong if you expected the style to be imported with link
  • Native: Behaves as expected of web components.

Template Inline Style

This is achievable with two methods:

  1. The styles can be wrapped in a style tag and placed before the templates:
@Component({
  template: `
    <style>
    h1 {
      color: purple;
    }
    </style>
    <h1>Styling Angular Components</h1>
    `
})
  1. The style can be written as normal inline styles in the template tags:
@Component({
  template: '<h1 style="color:pink">Styling Angular Components</h1>'
})

The expected behavior in various view encapsulation techniques are:

  • None: For method 1, the style is wrapped in a style tag and pushed to the head. It is appended right after the component inline and external styles. For method 2, the style just remains in the tag.
  • Emulated: For method 1, the style is wrapped in style tag, pushed to head, and uniquely identified so it can be matched with its component’s template just like the component inline style. For method 2, the style still remains in the tag.
  • Native: Behaves as expected of web components.

Style Priority

This is the point where we need to pay attention as it can be quite tricky. If you have been following the article carefully, you will realize that component styles, if any, are always appended to the head first.

Where it then becomes confusing is that in the first method of template inline styles are appended before the external styles. This makes external styles take precedence because in CSS the last is the greatest.

Playing With the Demo

To better understand priorities, I have created a Plunk with all the styling techniques we discussed. What I suggest is that you switch these styles, mess around with them and see the results. The comment section of this article is a great place to discuss your findings.

Conclusion

Whatever method you choose is accepted and that is the good thing about components and Angular 2. You don’t have to listen to the preaching of not using internal styles or inline styles as they are within components and will be scoped. On the other hand, we are now able to organize our code better in a modular pattern.

Angular 2 is awesome, right?


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
Leave a comment