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

陌路散爱 提交于 2019-12-13 04:12:45

问题


I'm using AngularElements with native encapsulation so bs4 components can be used in bs3 project. 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? Given NgbModalWindow component. How to change its encapsulation to ViewEncapsulation.Native and apply particular styles?

Here is related issue


回答1:


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. E.g. 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).

@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.

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. You can do this while bootstrapping your app module in main.ts file:

Change this: platformBrowserDynamic().bootstrapModule(AppModule) to this:

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.



来源:https://stackoverflow.com/questions/55733764/how-to-change-encapsulation-of-3rd-party-component-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!