【问题标题】:How to adjust mat-select height to fit its items?如何调整垫选择高度以适合其项目?
【发布时间】:2020-09-12 22:29:47
【问题描述】:

在 Angular 材质中,我需要根据项目列表动态增加垫选择的高度、开始和结束位置。例如,选项列表的范围可能从无到 100。所以高度应该适合内容,也不应该显示在我的应用程序屏幕之外。

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

谁能帮我在 CSS 中解决这个问题?

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

【问题讨论】:

    标签: html css angular angular-material


    【解决方案1】:

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

    就是,在 .html 中

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

    在你的 .ts 中,首先注入构造函数 Renderer2

    constructor(private renderer:Renderer2){}
    

    还有你的函数 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')
         }
    }
    

    你可以在this 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>
    

    见another stackblitz

    【讨论】:

    • 您的代码非常适合设置高度。是否可以使用 setStyle 设置边距顶部?
    • Renderer2 允许我们随心所欲地使用 setStyle - 你可以在同一个元素上多次使用 setStyle
    • 接收错误如果我设置 margin-top,则无法读取未定义的属性“nativeElement”
    • 我只是写this.renderer.setStyle(element.panel.nativeElement,'margin-top',"50px")然后工作。考虑到必须在if (event){..here..}-event 下获取值true,什么时候打开,如果不是false-
    • 您能否告诉我是否可以对多个 mat-select 使用相同的逻辑。目前我对多个 mat-select 使用相同的代码。这可能是错误的可能原因。
    猜你喜欢
    • 2018-09-16
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2021-08-31
    • 2016-06-13
    相关资源
    最近更新 更多