Tutorial

All the Ways to Add CSS to Angular 2 Components

Draft updated on Invalid Date
Default avatar

By Chris Nwamba

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?

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Chris Nwamba

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel