For every Angular component, we have a template (view) that we manage. We can also say that for every template, there is a stylesheet to apply to it. Sometimes it can prove challenging to manage stylesheets and importing them into our template. Thankfully, Angular gives support for injecting styles directly onto our view without interfering with other components.

By default, Angular uses a View Encapsulation strategy called Emulated Shadow DOM. This approach works in all browsers and works because Angular can scope the css for the component to only the component template by renaming the css selectors during compilation.

The other View Encapsulation modes are explained in detail here.

To utilize this new feature, simply make use of the styles or styleUrls metadata properties on your Component decorator. Here is an example of each use below:

@Component({
  selector: 'my-component',
  template: `<h1>Hello world!</h1>`,
  styles: ['h1 { color: red; }']
})
export class MyComponent {
  /* . . . */
}

Above, we are making the h1 tag in our template show as red text. However, unlike what we see in regular CSS files, the <h1> in our styles is only applied against the <h1> tag in our view. If you recall, this is because of the use of the Emulated Shadow DOM. Below is another example of how we can do this using URLs for our stylesheets.

@Component({
  selector: 'my-component',
  template: `<h1>Hello world!</h1>`,
  styleUrls: ['app/styles.css']
})
export class MyComponent {
  /* . . . */
}

Please be mindful that the URL used to locate your styles here should be relative to the application root and not your component! On most examples, the root of your project may be where the index.html file is located.

For more information on component styles, I suggest taking a deep look at the Official Tutorial on Component Styles by our friends at the Angular Team from Google.

 

I finished! On to the next tutorial