【问题标题】:How to change the touchUi property on mat-datepicker in Angular Material如何在 Angular Material 中更改 mat-datepicker 上的 touchUi 属性
【发布时间】:2018-11-16 06:01:43
【问题描述】:

我正在使用 Angular 5 和 Material Design 模块。

在我的 html 中,我有一个日期选择器:

<mat-datepicker touchUi=true #picker></mat-datepicker>

在我的 CSS 中,我设置了一些媒体查询:

/* Phones */
@media (max-width: 767px) {
}

/* Tablets */
@media (min-width: 768px) and (max-width: 991px) {
}

/* Desktops */
@media (min-width: 1200px) {
}

如何删除桌面的touchUi=true 属性?

【问题讨论】:

    标签: css angular angular-material


    【解决方案1】:

    您可以使用 Angular CDK 的 BreakpointObserver 以及 getter 来做到这一点。

    1. 从应用模块中的@angular/cdk/layout 导入LayoutModule

      import { LayoutModule } from '@angular/cdk/layout';
      // ...
      
      @NgModule({
          imports: [
              LayoutModule
          ]
      
    2. 使用来自@angular/cdk/layout 的断点观察器,如下所示(您可能需要BreakpointObserverisMatched 方法,它允许stringstring[] 作为媒体的参数):

      import { BreakpointObserver } from '@angular/cdk/layout';
      export class AppComponent {
          constructor(private breakpointObserver: BreakpointObserver){}
          // Check if device is phone or tablet
          get isMobile() {
              return this.breakpointObserver.isMatched('(max-width: 767px)');
          }
      }
      
    3. 在你的日期选择器中使用它:

      <mat-datepicker [touchUi]="isMobile" #picker></mat-datepicker>
      

    【讨论】:

    • 谢谢!我已经在研究@angular/flex-layout,所以我最终注入了 ObservableMedia 而不是 BreakPointObserver。其余代码的工作方式相同。
    • 如果视图中没有 mat-datepicker,在调整窗口大小时 Home 组件中的 getter 不会改变。但有了它,它就像魔法一样,黑暗魔法。我猜日期选择器正在触发一些事件,谁能给出更详细的解释?
    • mat-datepicker 是其中之一,工具提示和菜单也具有相同的效果。
    • 我想我的问题是:如何让 getter 在视图中没有任何材料组件的情况下工作?
    • 我明白了。只需为 window:resize 添加一个事件,不必为该事件做任何事情,但它会触发更改检测并使 getter 工作。
    【解决方案2】:

    Angular 使用Breakpoints.Handset 方法:

    component.ts:

      isHandset$: Observable<boolean> = this.breakpointObserver
        .observe(Breakpoints.Handset)
        .pipe(map(result => result.matches));
    
      constructor(private breakpointObserver: BreakpointObserver) {}
    

    html:

    <mat-datepicker [touchUi]="(isHandset$ | async) ? 'true' : 'false'" #picker></mat-datepicker>
    

    如果你问我,处理它的方式很干净。

    如果您想要一个完整的工作示例,请安装 navigation component schematic

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      相关资源
      最近更新 更多