首页 > 解决方案 > 设置 mat-select-panel 的最小宽度会在 Angular 2+ 中留下可见的动画

问题描述

我正在尝试重新定位 mat-select-panel,使其位于相应的下拉表单字段下方。使用此处提供的一些代码,我已经能够做到这一点。问题是,单击后,您可以看到面板更改大小。此行为在同一问题和接受的答案中提供的stackblitz中可见。到目前为止,我还没有找到解决方案。目前我在 styles.css 中的 .mat-select-panel 看起来像这样:

.mat-select-panel {
  position: absolute;
  top: 94px;
  left: 28px;
  min-width: calc(100% + 24px) !important;
  border-radius: 0px !important;
  border-top-style: none;
}

标签: cssangularanimation

解决方案


<mat-select>角度材质添加了跳跃动画,这就是它看起来宽度增加的原因。

简单的解决方案是禁用动画,但我找不到在特定元素/组件上禁用动画的解决方案

正如所说/讨论的herehere

禁用单个元素材质组件上的动画

//TS  
isDisabled = true;

//HTML
<div [@.disabled]="isDisabled">
 <div [@childAnimation]="exp"></div>
</div>

<mat-form-field appearance="outline">
 <mat-select [@.disabled]="isDisabled" placeholder="Favorite food" disableOptionCentering>
  <mat-option *ngFor="let food of foods" [value]="food.value">
   {{food.viewValue}}
  </mat-option>
 </mat-select>
</mat-form-field>

但不幸的是,这不起作用<mat-select>

禁用组件的动画

export class YourComponent {
 @HostBinding('@.disabled')
 public animationsDisabled = true;
}

这也不起作用。

什么是作品?

从组件禁用材质 cdk 覆盖(包括所有材质组件)的动画

import { Component, Renderer2 } from '@angular/core';
import { OverlayContainer } from '@angular/cdk/overlay';
...
overlayContainerElement: HTMLElement
constructor( private overlayContainer:OverlayContainer, private renderer:Renderer2) {
    this.overlayContainerElement = this.overlayContainer.getContainerElement();
    //To disable pass true as third argument
    this.renderer.setProperty( this.overlayContainerElement, "@.disabled", true );
}

注意:上面的代码禁用了整个应用程序的动画,如果你想禁用特定组件的动画,只需在你的组件中添加上面的代码并添加下面的代码来重新启用动画。

ngOnDestroy() {
 this.renderer.setProperty( this.overlayContainerElement, "@.disabled", false );
}

禁用整个应用程序的动画

您可以在主组件中添加上述代码(即,app.component.ts)或
替换BrowserAnimationsModuleNoopAnimationsModuleapp.module.ts

import { NoopAnimationsModule } from '@angular/platform-browser/animations';
...
@NgModule({
  imports:      [ NoopAnimationsModule ],
  declarations: [ ... ],
  bootstrap:    [ ... ]
})

工作示例(组件禁用动画)。


推荐阅读