ng-dropdown-panel in ng-select - how to keep its custom styles even when appendTo="body" is used

Viewed 8165

For demonstartions created a Stackblitz with almost an empty project with ng-select with no extra custom styles. And getting this issue of width of the ng-dropdown-panel when I am passing appendTo="body"

https://stackblitz.com/edit/github-byjnda

Details below

I am using ng-select and have quite a bit of custom styles defined to it as below in a .scss file using @mixin as below


@mixin custom-ng-select {
  @include custom-ng-select-ip();
  @include custom-text-body-light-2();

  caret-color: mat-color($sdk-secondary, 500);

  &.ng-select .ng-select-container {
    box-shadow: none;
    min-height: $custom-ng-select-height;
    display: flex;
    align-items: center;
  }

  &.ng-select.ng-select-single .ng-select-container {
    height: $custom-ng-select-height;
  }

 &.ng-select
    &.ng-dropdown-panel
    .ng-dropdown-panel-items
    .ng-option.ng-option-marked {
    padding-left: $custom-ng-select-pl;
    height: $custom-ng-select-height;
  }

...and many more styles...

And then in my Angular app's global styles.scss file getting this custom styles @mixin as below

.ng-select {
  @include custom-ng-select();
}

And this is working fine as expected.

But when I am rendering <ng-select> with appendTo="body" then the ng-dropdown-panel is no more taking the custom styles and the reason is as below per ng-select official doc

By default dropdown panel is rendered as child element of ng-select, but you can append dropdown to any element using appendTo

That is in below case ng-dropdown-panel is no more a child of ng-select

    <ng-select
      appendTo="body"
      [items]="items"
      [bindLabel]="'name'"      
    >
    </ng-select>

How do I do that, any guidance will be a life-saver.

Below screenshot is the top-most ng-select and this is how ng-dropdown-panel's custom styles is getting broken when using with appendTo="body"

enter image description here

And below screenshots where I have NOT used appendTo="body"

enter image description here

1 Answers

If you specify your class, you can access to the ng-dropdown-panel by your class.

<ng-select
  class="custom-class"
  appendTo="body"
  [items]="items"
  [bindLabel]="'name'"      
>
</ng-select>

Then you will have the custom class on ng-dropdown-panel in the html (like here), and you could access by scss:

ng-dropdown-panel.custom-class {
   min-width: 500px !important;
}

Note: I have ViewEncapsulation.None in the component for overriding ng-select styles:

@Component({
   selector: '...',
   templateUrl: './...],
   encapsulation: ViewEncapsulation.None
})

If you want to apply styles since another place, like styles.scss, maybe you have to override styles with ::ng-deep or something like that.

I hope I've helped

Update: If you want apply dynamic classes, you can try this workarround from yanotoma

Related