fetrarij / ngx-daterangepicker-material

Pure Angular 2+ date range picker with material design theme, a demo here:
https://fetrarij.github.io/ngx-daterangepicker-material/
MIT License
250 stars 255 forks source link

Clear daterange from external button #124

Closed frabanca closed 5 years ago

frabanca commented 5 years ago

Hi! I'm using this datepicker inside a component in an Angular 7 app, and since I'm using the daterange input to filter a Datatable I need to reset the input once the user click on a "Reset filters" custom button. How can I do that?

My code:

HTML code

  <input 
      type="text" 
      name="selectedDaterange"
      class="form-control"
      ngxDaterangepickerMd
      [(ngModel)]="selectedDaterange" 
      [ranges]="ranges"
      [alwaysShowCalendars]="true"
      [showClearButton]="true"
      placeholder="Choose date"
      (ngModelChange)="onSelectedDaterangeChange()"/>
  </div> <!-- /.input-group -->

  <button class="btn btn-outline-info" type="button" (click)="onFilterFormClear()" >
    Clear filters
  </button>

Typescript code

export class MyComponent implements OnInit, OnDestroy {
  ... // Custom code
  selectedDaterange: {
    startDate: moment.Moment,
    endDate: moment.Moment
  };
  ranges: any = {
    'Today': [moment(), moment()],
    'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
    'Last 7 Days': [moment().subtract(6, 'days'), moment()],
    'Last 30 Days': [moment().subtract(29, 'days'), moment()],
    'This Month': [moment().startOf('month'), moment().endOf('month')],
    'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
  };

  /**
   * Handle filter cleaning and redraw datatable
   */
  onFilterFormClear(): void {
    this.dateFilter = '';

    // this.selectedDaterange = null; // This doesn't work since it through a console error like this: ERROR TypeError: Cannot read property 'endDate' of null

    ... // Reset other filters
    this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
      dtInstance.draw();
    });
  }

  ... // other component's code
frabanca commented 5 years ago

My bad, after a careful reading of your demo code I realized I can use the this.picker.clear() which doesn't throw any error.

Thanks

tony-eneh commented 1 year ago

How do I get a reference to this.picker in this case?

sahusudheer commented 8 months ago

use view child and get the picker directive reference