Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 setting view encapsulation globally

Tags:

angular

I've decided to set ViewEncapsulation to None for all my components in my project.

So, how can I set ViewEncapsulation.None globally to whole project? instead of setting it in each of my components decorator.

Note: Just for extra info, My deps are on RC.6

Edit: The 2nd solution provided by Günter Zöchbauer also works on 2.1.2

like image 671
choz Avatar asked Sep 12 '16 14:09

choz


People also ask

What is the default view encapsulation in Angular?

View Encapsulation - Rangle.io : Angular Training. View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa. Angular provides three encapsulation strategies: Emulated (default) - styles from main HTML propagate to the component.

What is view encapsulation none?

ViewEncapsulation.None. Angular does not apply any sort of view encapsulation meaning that any styles specified for the component are actually globally applied and can affect any HTML element present within the application. This mode is essentially the same as including the styles into the HTML itself.

Is the default ViewEncapsulation mode?

Emulated. The Emulated mode is the default one. This allows that styles from main HTML propagate to the component but styles defined in this component's @Component decorator are scoped to this component only.


1 Answers

You can set default view encapsulation by passing a custom CompilerConfig. This feature was added in RC.2 (last item in the features list)

1. You can set it on NgModule level

this way doesn't work anymore

    @NgModule({
        // imports, declaration, bootstrap, etc..
        providers: [{
            provide: CompilerConfig, 
            useValue: new CompilerConfig({
                defaultEncapsulation: ViewEncapsulation.None
            })
        }]
    })
    export class AppModule {}

Plunker example

2. Set it on bootstrap level (Thanks to yurzui)

platformBrowserDynamic().bootstrapModule(AppModule, [
    {
        defaultEncapsulation: ViewEncapsulation.None
    }
]);

Please note that you ofc need to import ViewEncapsulation from @angular/core

3. In more recent Angular versions this can be set in compiler options

Caution: I haven't tried this myself yet. This is just how I interpreted the docs:

In tsconfig.json

{ 
  ...,
  angularCompilerOptions: {
   defaultEncapsulation: 3;
  }
}
 
  • https://angular.io/guide/angular-compiler-options
  • https://angular.io/api/core/CompilerOptions
  • https://angular.io/api/core/ViewEncapsulation
like image 168
Günter Zöchbauer Avatar answered Oct 14 '22 00:10

Günter Zöchbauer