防止全局 CSS 被应用到 Angular 中的组件 5

Prevent global CSS being applied a component in Angular 5

.angular-cli.json中,我得到了一些全局样式:

"styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.css",
        "../node_modules/ng2-toastr/bundles/ng2-toastr.min.css",
        "styles.scss"
    ],

但我不希望 任何 应用到特定组件 - 它可以实现吗?

编辑 1:
不幸的是,覆盖组件样式中的 CSS 样式将不起作用,因为组件模板中的 HTML 是从 Web API 后端获取的 - 我想我不能现实覆盖所有可能的 class/selector?

您可以在@Component 范围内使用 styleUrls 属性 在组件级别定义样式。请看下面的代码:-

@Component({
selector: 'app-manageUser',
templateUrl: './manageUser.component.html',
styleUrls: ['./manageUser.component.css'],
providers: [UserService]
})

使用组件样式 对于您编写的每个 Angular 组件,您不仅可以定义一个 HTML 模板,还可以定义该模板附带的 CSS 样式,指定您选择的任何选择器、规则和媒体查询需要。

一种方法是在组件元数据中设置样式 属性。样式 属性 采用包含 CSS 代码的字符串数组。通常你给它一个字符串,如下例所示:

@Component({
  selector: 'app-root',
  template: `
    <h1>Test Text</h1>      
  `,
  styles: ['h1 { font-weight: normal; }']
})
export class AppComponent {
/* . . . */
}

styleUrls
包含要在此组件中使用的 CSS 样式表的文件的一个或多个 URL。

styleUrls: string[]

样式
要在此组件中使用的一个或多个内联 CSS 样式表。

styles: string[]

您可以在全局 CSS 中使用 :not 选择器。

您必须尝试使用​​它才能获得所需的行为,但它应该是这样的:

h1:not(.my-specific-class) {
  font-size: 3rem;
}

CSS 级联(因此称为级联样式表)。 要获得完整的浏览器支持,您唯一的选择是覆盖选择器。

另一种选择,由于 缺乏对 IE 和 Edge 的支持,因此不常见 就是all属性。

html

<div class="component-container">
  <!-- your components html template ... -->
</div>

css

.component-container {
  all: initial;
  all: unset;
}

您可以使用 shadowDom API 中内置的 angular 来自 查看封装 。这将使您的组件元素加载到单独的 DOM 树中,因此全局 css 不会影响您的组件元素。

   @Component({
  selector: 'app-root',
  template: `
    <h1 class="head-app">Test Heading</h1>      
  `,
  styles: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class AppComponent {
/* . . .