Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the touchUi property on mat-datepicker in Angular Material

I am using Angular 5 with the Material Design modules.

In my html, I have a datepicker:

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

In my CSS I set up some media queries:

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

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

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

How can I remove the touchUi=true property for desktops?

like image 910
Martijn Burger Avatar asked Dec 18 '22 02:12

Martijn Burger


2 Answers

You can use Angular CDK's BreakpointObserver to do that, as well as with getters.

  1. Import LayoutModule from @angular/cdk/layout in your app's module:

    import { LayoutModule } from '@angular/cdk/layout';
    // ...
    
    @NgModule({
        imports: [
            LayoutModule
        ]
    
  2. Use the breakpoint observer from @angular/cdk/layout as follows (you probably want the isMatched method of BreakpointObserver which allows a string or string[] as its param for the media):

    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. Use it as follows in your datepicker:

    <mat-datepicker [touchUi]="isMobile" #picker></mat-datepicker>
    
    • Official documentation
    • API Docs
    • Stackblitz Demo
like image 119
Edric Avatar answered Jan 01 '23 23:01

Edric


Angular uses the Breakpoints.Handset methodology:

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>

Pretty clean way of handling it if you ask me.

If you want a full working example, install the navigation component schematic

like image 28
rynop Avatar answered Jan 02 '23 00:01

rynop