简体   繁体   中英

ng-deep causing issues with mat-select in Angular

I am using mat-select from angular. I have used it in 2 places.

  1. AppComponent
  2. ModalComponent

In order to style the options panel in mat-select I have used ng-deep as follows,

In app.component.css

::ng-deep .mat-select-panel {
  border-top: none !important;
  min-width: 100% !important; 
  position: absolute;
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.15);
  margin-left: 17px !important;
  margin-top: -10px !important;
}

This was positioned correctly until another modal element was added to the page. In this modal component, ng-deep is also been used in order to style the mat-select within the modal. In modal.component.css

::ng-deep .mat-select-panel {
  min-width: calc(100% + 7px) !important;
  position: absolute;
  top: 100px;
  left: 20px;
}

So now when we click on the mat-select in the modal component and then if we click on the mat-select in app component, the position of the mat-select in the app component seems to be in a different position. Can someone please help me fix this issue.

ng-deep is deprecates, so you should use component without encapsulation, so:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class AppComponent {}

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class ModalComponent {}

The css classes you have created should encapsulate it within a div with another class and define them this way:

app.component.css

.custom1 .mat-select-panel {
  border-top: none !important;
  min-width: 100% !important; 
  position: absolute;
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.15);
  margin-left: 17px !important;
  margin-top: -10px !important;
}

app.component.html

<div class="custom1">
  <!-- here mat-select whith class .mat-select-panel -->
</div>

modal.component.css

.custom2 .mat-select-panel {
  min-width: calc(100% + 7px) !important;
  position: absolute;
  top: 100px;
  left: 20px;
}

modal.component.html

<div class="custom2">
  <!-- here mat-select whith class .mat-select-panel -->
</div>

For more information see:

https://angular.io/guide/component-styles#view-encapsulation

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

https://material.angular.io/guide/theming#defining-a-custom-theme

I was able to fix this using panel class.

<div class="custom">
  <mat-select panelClass="select-panel"></mat-select> 
</div>

Then in styles.css

.custom .select-panel{
  min-width: calc(100% + 7px) !important;
  position: absolute;
  top: 100px;
  left: 20px;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM