mat-datepicker opens in different place

903 Views Asked by At

I have my mat-datepicker in 2 places on the page. And when I'm clicking on the one place, it opens in an oposite place. How can I fix that? I have 2 different components with mat-datepicker, but it opens different. Maybe the problem is that I imitate click in one component? But why it opens different one? Here's the code

Opens here: (child.components.html)

<mat-form-field appearance="fill">
      <input matInput [matDatepicker]="picker">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker ngDefaultControl></mat-datepicker>
    </mat-form-field>

Clicks here: (parent.component.html)

<mat-form-field appearance="fill">
        <mat-label>Choose a date</mat-label>
        <input [min]="minDate" (dateInput)="onDate($event)" matInput [matDatepicker]="picker" (keydown)="false">
        <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
        <mat-datepicker #picker ngDefaultControl></mat-datepicker>
      </mat-form-field>

Onchange event opens Calendar like this:

 public onTabChange(event: MatButtonToggleChange): void {
      setTimeout(() => {
        const element: HTMLElement = document.getElementsByClassName('mat-icon-button')[0] as HTMLElement;
        element.click();
      }, 200);
  }
1

There are 1 best solutions below

0
On BEST ANSWER

try give differents "template reference variable" (replace one #picker by, e.g. #picker2 and replace the picker by picker2.

About imitate click (it's not the problem) I suggest use a ViewChild and directly use open method

import {MatDatepicker} from '@angular/material/datepicker';

@ViewChild('picker2') datepicker:MatDatepicker<any>

public onTabChange(event: MatButtonToggleChange): void {
      setTimeout(() => {
        this.datepicker.open()
      });
  }

See that you needn't "wait" the 200 miliseconds. The setTimeout say to angular: "hey you!, repaint the app and after, remember execute the code under the setTimeout" -the same happens if you use change detector and use .markForCheck()-