如何在选择(Angular material 7)下显示选项?

问题描述 投票:1回答:2

如何在选择(Angular material 7)下显示选项? enter image description here

像默认选择:

enter image description here

angular html-select angular-material2 angular-material-6
2个回答
1
投票

“正确”的答案是在mat-select上使用disableOptionCentering,但即使这样也只能防止占位符被覆盖,并且不会模仿基本的原生选择。

<mat-select placeholder="Favorite food" disableOptionCentering>

在Angular中对DOM中的本机元素进行DOM操作是非常不受欢迎的,但不幸的是,这是我发现做这样的事情的唯一方法......

  • 希望有人会发布一种真正的“Angular”方式来做这种事情,因为我发现自己因为这些原因而操纵材料库。

您将需要使用div包装器包装您的选项并分配templateRef #matOptionDiv,以便您可以在组件中使用它来获取选项下拉列表的父元素,即CDK叠加层。

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

然后使用mat-form-field上的click事件触发组件中的方法以对齐叠加层

<mat-form-field (click)="positionDropDown()">

然后在你的组件中使用@ViewChild来获取templateRef

import {Component, ViewChild} from '@angular/core';

@ViewChild('matOptionDiv') _matOptionDiv:any;

然后创建您的方法来计算叠加层上的新top值并分配它... setTimout是触发更改与摘要周期所必需的。

positionDropDown(){
  let offsetY = 
  this._matOptionDiv.nativeElement.parentElement.parentElement.style.top

  setTimeout(()=>{this._matOptionDiv.nativeElement.parentElement.parentElement.style.top = parseInt(offsetY.slice(0, -2))+40+'px'},0)
  }

这是一个非常“hacky”的解决方案,并不漂亮,希望有人会在某个时候发布一个真正的“Angular”解决方案来回答这个问题。

  • 不幸的是,在mat-select的源代码中发生了计算,以编程方式通过_calculateOverlayOffsetY基于可查看区域定义覆盖的顶部......这些都没有在API中公开,因此我无法“正确”操作它我担心DOM操纵可能是唯一的方法。

https://github.com/angular/material2/blob/6d7f41739207e469e626963d64e661401629902d/src/lib/select/select.ts#L1154

这是Stackblitz供您查看。

https://stackblitz.com/edit/angular-nafuur?embed=1&file=app/select-overview-example.ts

调整

我做了一些关于这方面的研究,只要你使用Renderer2与DOM适配器接口并且“适当地”更新DOM ......使DOM更改平台独立,角色就可以接受DOM操作。

有关更多信息,请参阅此youTube视频。

Can't Touch This! What not to do to the DOM by Max NgWizard


Stackblitz代码更新如下

import {Component, ViewChild, ElementRef, Renderer2} from '@angular/core';

@ViewChild('matOptionDiv') _matOptionDiv:ElementRef;

constructor(private renderer: Renderer2) { }

 positionDropDown() {
    let offsetY = this._matOptionDiv.nativeElement.parentElement.parentElement.style.top;

    setTimeout(() => {
      // this._matOptionDiv.nativeElement.parentElement.parentElement.style.top = parseInt(offsetY.slice(0, -2))+40+'px'},0)
      this.renderer.setStyle(this.renderer.parentNode(this.renderer.parentNode(this._matOptionDiv.nativeElement)), 'top', parseInt(offsetY.slice(0, -2)) + 40 + 'px');
    });
  }

0
投票

您从中获取屏幕截图的文档全面概述了如何包含此组件,只需确保按下

<>

在创建它的代码的示例的右上角。如果它是特定的东西你正在努力发布你得到的错误

https://material.angular.io/components/select/overview

© www.soinside.com 2019 - 2024. All rights reserved.