简体   繁体   English

如何在Angular中更改第三方组件的封装?

[英]How to change encapsulation of 3rd party component in Angular?

I'm using AngularElements with native encapsulation so bs4 components can be used in bs3 project. 我正在使用带有本机封装的AngularElements,因此可以在bs3项目中使用bs4组件。 Example: 例:

@Component({
  selector: 'app-my-button',
  templateUrl: './my-button.component.html',
  encapsulation: ViewEncapsulation.Native,
  styles: ['@import "~bootstrap/scss/bootstrap.scss";']
})
export class MyButtonComponent {}

The question is how to change encapsulation of 3rd party component so that global css doesn't affect it? 问题是如何更改第三方组件的封装,以便全局css不会影响它? Given NgbModalWindow component. 给定NgbModalWindow组件。 How to change its encapsulation to ViewEncapsulation.Native and apply particular styles? 如何将其封装更改为ViewEncapsulation.Native并应用特定样式?

Here is related issue 这是相关问题

If you use a third party component inside a component whose encapsulation is set to native, global styles wont apply to that third party component. 如果在其encapsulation设置为本机的组件内使用第三方组件,则全局样式将不适用于该第三方组件。 Eg If you use the third party component ngb-modal-window inside your own component lets say app-my-own-component whose encapsulation is set to native, the global styles wont apply to ngb-modal-window because it will be inside shadow root(of the parent app-my-own-component ). 例如,如果您在自己的组件中使用第三方组件ngb-modal-window ,请说app-my-own-component其封装设置为native,全局样式将不适用于ngb-modal-window因为它将在阴影内root(父app-my-own-component )。

@Component({
  selector: 'app-my-own-component',
  template: '<ngb-modal-window></ngb-modal-window>',
  encapsulation: ViewEncapsulation.Native,
  styles: ['@import "~bootstrap/scss/bootstrap.scss";']
})

However adding styles in app-my-own-component will get applied to ngb-modal-window in this case. 但是,在这种情况下,在app-my-own-component添加样式将应用于ngb-modal-window

Another thing you can do is set encapsulation to ViewEnacpsulation.Native at global level so that all components in you application will have Native encapsulation. 您可以做的另一件事是在全局级别将encapsulation设置为ViewEnacpsulation.Native ,以便您应用程序中的所有组件都具有Native封装。 You can do this while bootstrapping your app module in main.ts file: 您可以在main.ts文件中引导app模块时执行此操作:

Change this: platformBrowserDynamic().bootstrapModule(AppModule) to this: 将此: platformBrowserDynamic().bootstrapModule(AppModule)更改为:

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

You will have to import ViewEncapsulation inside main.ts of whatever the name of the file is where you are bootstrapping your module. 您必须在main.ts中导入ViewEncapsulation ,无论文件名是什么,您都可以在模块的引导位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM