如何在 angular 11.2 中止血 css

How to stop css bleeding in angular 11.2

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

如果您在 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 {
/* . . . */
}

在组件声明中使用 encapsulation

@Component({

selector:'app-component',

templateUrl:'app.compionent.html',

encapsulation:ViewEncapsulation.None,

})

我的解决方案是使用 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 然后按照这个方法。