简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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