Angular2 Quicky - ViewEncapsulation.Native in all browsers

Angular2 Quicky - ViewEncapsulation.Native in all browsers

A few days ago I wrote about ViewEncapsulation over here. The sample I demonstrated over there was only working in Chrome. The following lines will explain why and how to get those samples working in all modern browsers.

By default ng2 is using ViewEncapsulation.Emulated to render your components. Emulated means that you're not using native ShadowDOM features, instead Angular2 does some refactoring to both, your template and your styles, to encapsulate those from the rest of your app and render everything as expected. (see the linked article above for more details).

This emulation will also be used if the browser has built-in support for ShadowDOM.

If you force Angular to use Native view encapsulation for your components by decorating them like this

import {Component, ViewEncapsulation} from 'angular2/core'

@Component({
  selector: 'todo-item',
  templateUrl: 'templates/todoitem.html',
  styleUrls: ['styles/todoitem.css']
  encapsulation: ViewEncapsulation.Native
})
export class TodoItemComponent {}  

Angular2 will rely on official ShadowDOM specs and let browsers decide how to deal with your components. Everything works fine in Google Chrome and Opera, but unfortunately there are more browsers in the wild than these.

Both, Chrome and Opera are supporting ShadowDOM without using any kind of polyfills. But when users browse your app with Edge or Firefox, they will see just nothing because those browsers neither have any native implementation for ShadowDOM nor they're shipping any polyfill out of the box. Angular2 tries to render your app and it will crash as soon as the ShadowDOM API will be called by ng2.

In order to get ViewEncapsulation.Native working across all browsers, you've to add a script reference to WebComponentsJs (see https://github.com/webcomponents/webcomponentsjs) to your HTML page. WebComponentsJs will add the required polyfills at runtime (only if the browser doesn't provide some)

Some of you may also know project polymer which was targeting also the same issue. Polymer is now part of WebComponentsJs, so you don't have to make a decision here.

Comments

comments powered by Disqus