【问题标题】:How to stop css bleeding in angular 11.2如何在 Angular 11.2 中停止 CSS 流血
【发布时间】:2021-07-21 03:10:00
【问题描述】:

我正在处理一个 Angular 11.2 项目,我看到一个组件的 CSS 正在应用于另一个具有相同 css 选择器名称的组件。我怎样才能阻止这个?请帮忙

【问题讨论】:

    标签: css angular angular2viewencapsulation


    【解决方案1】:

    如果你在 Angular @component 中应用样式,它应该只应用于那个组件范围。

    https://angular.io/guide/component-styles

    @Component({
      selector: 'app-root',
      template: `
        <h1>Tour of Heroes</h1>
        <app-hero-main [hero]="hero"></app-hero-main>
      `,
      styles: ['h1 { font-weight: normal; }']
    })
    export class HeroAppComponent {
    /* . . . */
    }
    

    【讨论】:

    • 我正在使用模板
    • 是的,但是您使用的是 'styles' 属性吗?如果没有,请向容器中添加一个类,并手动将 CSS 范围限定为相关容器。
    【解决方案2】:

    在你的组件声明中使用encapsulation

    @Component({
    
    selector:'app-component',
    
    templateUrl:'app.compionent.html',
    
    encapsulation:ViewEncapsulation.None,
    
    })
    

    【讨论】:

    • 我猜你想说:'encapsulation:ViewEncapsulation.Emulated':None 表示 Angular 不查看封装。 Angular 将 CSS 添加到全局样式中,因此 CSS 选择器名称规则将应用于具有相同 css 选择器名称的另一个组件。 Emulated 选项(默认)通过预处理(和重命名)CSS 代码来模拟 shadow DOM 的行为,从而有效地将 CSS 限定在组件的视图中
    • 是的,我试过了,但在这样做之后,我无法定位库 css 类。如何使用 emulated 但仍然能够针对 3rd 方库组件的 css 类?
    【解决方案3】:

    我的解决方案是使用 ViewEncapsulation.None,但使用目标 css。即使用特异性。例如,如果我的组件结构如下:

    <div class="parent">
      <div class="child">
        <span></span>
      </div>
    </div>
    

    我的 CSS 是:

    .parent .child > span { ...some css here}
    

    不使用 Emulated 的原因是,某些 lib 组件不能以“None”作为 ViewEncapsulation 的目标。因此我们需要将其设置为 None ,然后按照这种方法。

    【讨论】:

      猜你喜欢
      • 2019-11-12
      • 1970-01-01
      • 2021-06-16
      • 2014-12-16
      • 2023-03-28
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      相关资源
      最近更新 更多