首页 > 解决方案 > Angular: setting ViewEncapsulation.None globally

问题描述

In my project, Angular adds css classes to HTML elements and components at runtime :

<div class="ng-tns-c99-6">..</div>

I've tried :

encapsulation: ViewEncapsulation.None

but it still adds the CSS class at runtime.

I found this answer here and tried to set ViewEncapsulation.None globally, but this doesn't affect it either, the CSS classes are still being added.

Is there a way to turn it off?

标签: angular

解决方案


It is not possible to set ViewEncapsulation globally. Issue 18346 on GitHub suggests to allow setting it at the module level. The status of the issue is Open at the present moment.

Set ViewEncapsulation per module #18346

Current behavior

Currently, we set the view encapsulation at the component level.

@Component({
  selector: 'song-track',
  encapsulation: ViewEncapsulation.Native
})
Meaning that if I want to use native Shadow DOM throughout my app, 
I have to add that bit of configuration to every single component.

Expected behavior

It would be great if I could set it at the module level.

@NgModule({
  imports: [...],
  declarations: [...],
  providers: [
      ...
      { provide: ViewEncapsulationMode, useValue: ViewEncapsulation.Native },
      ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

推荐阅读