-2

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

4

3 回答 3

2

如果您在 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 {
/* . . . */
}
于 2021-06-27T06:18:23.247 回答
0

encapsulation在您的组件声明中使用

@Component({

selector:'app-component',

templateUrl:'app.compionent.html',

encapsulation:ViewEncapsulation.None,

})
于 2021-06-27T06:26:46.760 回答
0

我的解决方案是使用 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 然后遵循这种方法。

于 2021-07-20T19:10:00.787 回答