如何调整垫子选择高度以适合其项目? [英] How to adjust mat-select height to fit its items?

查看:38
本文介绍了如何调整垫子选择高度以适合其项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular材料中,我需要根据项目列表动态增加垫选的高度,起点和终点.例如,选项列表的范围可能从无到100.因此高度应适合内容并且也不应显示在我的应用程序屏幕之外.

In Angular material, I need to increase the height, start and end position of a mat-select dynamically based on list of items. For example, list of options may range from none to 100. So the height should fit to the content and also should not display outside of my application screen.

我使用以下样式,但是当我有更多项目时,前几个项目没有显示在屏幕上.如果我使用margin-top,则会在屏幕顶部的另一个下拉菜单中破坏设计.因此,无论下拉菜单位置如何,它都应以最大高度显示在我的屏幕内.

I used below style but when I have more items, first few items are not getting displayed in screen. If I use margin-top, it breaks the design in another dropdown which is located on top position of my screen. So irrespective of dropdown position, it should display inside my screen with maximum height.

能帮我在CSS中解决此问题吗?

Can any help me to fix this in CSS?

.mat-select-panel {
    max-height: 95vh !important;
  }

推荐答案

您可以使用事件(openedChange)使用Renderer2更改选择面板的高度

you can use the event (openedChange) to change the heigth of the select-panel using Renderer2

多数民众赞成在.html

Thats, in .html

<mat-select #select (openedChange)="changeHeight($event,select)">
    <mat-option>...</mat-option>
    <mat-option>...</mat-option>
</mat-select>

在您的.ts文件中,首先注入构造函数Renderer2

In your .ts, first inject in constructor Renderer2

constructor(private renderer:Renderer2){}

您的函数changeHeight

And your function changeHeight

changeHeight(event:any,element:any)
{
    if (event)
    {
      //get the height of the "screen"
      const height = window.innerHeight|| 
                     document.documentElement.clientHeight|| 
                     document.body.clientHeight;
      //the max-height will be the height of the screen - the position of pannel
      // - 10 px (you can change this last one)
      this.renderer.setStyle(element.panel.nativeElement,
          'max-height',
           (height-10-element.panel.nativeElement.getBoundingClientRect().y)+'px')
     }
}

您可以在此stackblitz

您还可以发出指令

@Directive({
  selector: "[autosize]"
})
export class AutosizeDirective {
  @HostListener("openedChange", ["$event"])
  changeHeight(event: any) {
    if (event) {
      const height =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      this.renderer.setStyle(
        this.select.panel.nativeElement,
        "max-height",
         (height -10 -this.select.panel.nativeElement.getBoundingClientRect().y) +"px");
    }
  }
  constructor(@Host() private select: MatSelect, private renderer: Renderer2) {}
}

并使用类似

<mat-select autosize>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
</mat-select>

请参见另一个stackblitz

这篇关于如何调整垫子选择高度以适合其项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆