简体   繁体   中英

How to implement a Date Range Picker using mat-calendar in Angular

I would like to implement a Daterange picker using mat-calendar in Angular. I am not able to get implement it in a correct way. Can anyone help me in this.

My html code:

<mat-calendar [selected]="range"
[comparisonStart]="range.start"
[comparisonStart]="range.end"
(selectedChange)="onChange($event)"></mat-calendar>

My Ts Code:

range: DateRange<Date>;
constructor(){}
ngOnInit(){
}
 onChange(event)
 {
  console.log(event);
 }

Note: mat date range picker only work on Angular 10 and above

* .component.html

<mat-form-field appearance="fill">
  <mat-label>Enter a date range</mat-label>
  <mat-date-range-input [formGroup]="range" [rangePicker]="picker">
    <input matStartDate formControlName="start" placeholder="Start date">
    <input matEndDate formControlName="end" placeholder="End date">
  </mat-date-range-input>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>

  <mat-error *ngIf="range.controls.start.hasError('matStartDateInvalid')">Invalid start date</mat-error>
  <mat-error *ngIf="range.controls.end.hasError('matEndDateInvalid')">Invalid end date</mat-error>
</mat-form-field>

<button (click)="save()">Save</button>
<p>Selected range: {{range.value | json}}</p>

* .component.ts

import { Component } from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  range = new FormGroup({
    start: new FormControl(),
    end: new FormControl()
  });
  constructor(){

  }
}

app.module.ts

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

Example: https://stackblitz.com/angular/dmojaobybmm?file=src%2Fapp%2Fdate-range-picker-forms-example.ts

i follow here https://github.com/angular/components/issues/20307#issuecomment-674040060

here's a working example https://stackblitz.com/edit/components-issue-q9db1k .

if u want code inside Onchange, here is my code

just process with logic:D here is my code:

<mat-calendar #calendar [selected]="selectedDateCalendar" (selectedChange)="toggleStartDateDate($event, calendar)">

in ts: just declare start, end, selectDateType

toggleStartDateDate(date: any, calendar: any) {
const selected_date = moment(date).toDate()
if (this.selectDateType === "startDateAfter") {
  this.start = selected_date
  this.end = selected_date
  this.selectDateType = "startDateBefore"
} else {
  if (moment(date).isBefore(moment(this.start))) {
    this.start = selected_date
    this.end = selected_date
    this.selectDateType = "startDateBefore"
  } else {
    this.end = selected_date
    this.selectDateType = "startDateAfter"
  }
}
this.selectedDateCalendar = new DateRange(moment(this.start), moment(this.end))
calendar.updateTodaysDate()}

You have to provide a range selection strategy to get the preview working.

  providers: [
    {
      provide: MAT_DATE_RANGE_SELECTION_STRATEGY,
      useClass: DefaultMatCalendarRangeStrategy,
    },
  ],

Then, you'd have to do some converting of Date to DateRange .

  selectedDateRange: DateRange<Date>;

  _onSelectedChange(date: Date): void {
    if (
      this.selectedDateRange &&
      this.selectedDateRange.start &&
      date > this.selectedDateRange.start &&
      !this.selectedDateRange.end
    ) {
      this.selectedDateRange = new DateRange(
        this.selectedDateRange.start,
        date
      );
    } else {
      this.selectedDateRange = new DateRange(date, null);
    }
  }
<mat-calendar (selectedChange)="_onSelectedChange($event)"
              [selected]="selectedDateRange">
</mat-calendar>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM