首页 > 解决方案 > 如何阻止父组件css不覆盖子组件css(Angular 5)?

问题描述

<mat-select>在我的导航栏中使用,它在不同的页面中使用。我也在<mat-select>我的一种形式中使用它,它有一个下拉菜单。我注意到当我使用 时::ng-deep,它也会覆盖<mat-select>其他组件中的 CSS。我也尝试过封装,但这不起作用。

导航栏

::ng-deep .mat-select-panel {
  margin-left: -22.75rem;
  margin-top: 2.875rem;
  font-size: 14px;
}
<mat-select formControlName="state">
    <mat-option  class="my-component" *ngFor="let city of cities"[value]="city.abbrev">{{ city.abbrev }}
    </mat-option>
</mat-select>

这会覆盖任何其他正在使用<mat-select>的组件,因为组件 NAV-BAR 正在整个应用程序中使用。我怎样才能将它用于导航栏,而不是让它覆盖其他组件?

标签: angularangular-material

解决方案


看起来你需要使用panelClass

所以你可以制作包装器组件

@Component({
  selector: 'wrapper',
  template: '<ng-content></ng-content>',
  styles: [`.make-it-green-again {
    background: green;
  }`],
  encapsulation: ViewEncapsulation.None,
})
export class WrapperExample {
  @ContentChild(MatSelect, {static: false})
  element: MatSelect;

    ngAfterContentInit() {
    if(this.element){
      this.element.panelClass = 'make-it-green-again'
    }
  }
}

然后在你的html中

  <wrapper>
    <mat-select>
      <mat-option>None</mat-option>
      <mat-option value="option1">Option 1</mat-option>
      <mat-option value="option2">Option 2</mat-option>
      <mat-option value="option3">Option 4</mat-option>
    </mat-select>
  </wrapper>
</mat-form-field>

<mat-select  >
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 4</mat-option>
  </mat-select>

推荐阅读