Angular中如何仅为使用第三方库的单个组件引入其样式
I get that you want to avoid polluting your global styles with Chartist's CSS and only load it for the specific component that uses the library. Let's fix that issue where importing the styles in your component's SCSS file wasn't working.
Why the Initial Approach Failed
Angular uses ViewEncapsulation.Emulated by default for components. This adds unique attribute selectors (like [_ngcontent-xyz]) to your component's styles, ensuring they only apply to elements within that component. However, Chartist's styles target global classes (e.g., .ct-chart) without these custom attributes, so they can't match the elements in your component when imported directly.
Solution 1: Use ::ng-deep to Penetrate Encapsulation
This method lets you keep Angular's default encapsulation while making the imported Chartist styles apply to your component's DOM. Just wrap the @import statement in ::ng-deep in your chartist.component.scss:
::ng-deep { @import '~chartist/dist/scss/chartist.scss'; }
::ng-deep removes the component-specific attribute prefix from the imported styles, allowing them to target the .ct-chart element in your template. The styles will still be scoped to your component (won't leak to other parts of the app) because they're wrapped in the component's style context.
Solution 2: Disable View Encapsulation for the Component
If you prefer not to use ::ng-deep, you can turn off view encapsulation entirely for this component. This makes the component's styles act like global styles, but since you're only importing Chartist here, it won't affect other components unless they also use Chartist classes.
Update your component decorator to include encapsulation: ViewEncapsulation.None:
import { Component, Input, AfterViewInit, ViewEncapsulation } from '@angular/core'; import * as Chartist from 'chartist'; @Component({ selector: 'chartist', template: ` <h1>Here is chartist chart:</h1> <div class="ct-chart" id="chart" ></div> `, styleUrls: ['./chartist.component.scss'], encapsulation: ViewEncapsulation.None // Add this line }) export class ChartistComponent implements AfterViewInit { @Input() name: string; data: any = { labels: [ 'Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], series: [[542, 443, 320, 780, 553, 453, 326, 434, 568, 610, 756, 895]] }; ngAfterViewInit() { const optionsEmailsSubscriptionChart = { axisX: { showGrid: true }, low: 0, high: 1000, chartPadding: { top: 0, right: 5, bottom: 0, left: 0 } }; setTimeout(() => { const emailsSubscriptionChart = new Chartist.Bar( '#chart', this.data, optionsEmailsSubscriptionChart ); }, 1000); } }
Then keep your chartist.component.scss as is:
@import '~chartist/dist/scss/chartist.scss';
Either of these approaches will make the Chartist styles apply only to your chartist component—no need to import them globally in styles.scss.
内容的提问来源于stack exchange,提问作者happyZZR1400

