Search code examples
javascriptangulardatepickerangular-ui-bootstrapng-bootstrap

Remove date from ToDate on selection of fromDate in ng-Bootstrap


I want to clear date from toDate while selecting date from fromDate in ng-bootstrap.

<form class="row row-cols-sm-auto" *ngIf="showDateRangeImp">
    <div class="col-12">
        <div class="input-group">
            <input class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #d1="ngbDatepicker"
                (dateSelect)="impOnDateSelection($event,'from')" [maxDate]="minDate" />
            <button class="btn btn-outline-secondary bi bi-calendar3" (click)="d1.toggle();" type="button"></button>
        </div>
    </div>
    <div class="col-12">
        <div class="input-group">
            <input class="form-control" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker #d2="ngbDatepicker"
                (dateSelect)="impOnDateSelection($event,'to')" [maxDate]="minDate" (input)="model" />
            <button class="btn btn-outline-secondary bi bi-calendar3" (click)="d2.toggle();" type="button"></button>
        </div>
    </div>
</form>

Solution

  • This is one way of clearing the date

    • Use ngModel and bind the date picker values to the ts file
    • When impOnDateSelection is triggered check the date picker type and rest the model value
    <div class="row row-cols-sm-auto" *ngIf="showDateRangeImp">
      <div class="col-12">
        <div class="input-group">
          <input
            class="form-control"
            placeholder="yyyy-mm-dd"
            name="dp"
            ngbDatepicker
            #d1="ngbDatepicker"
            (dateSelect)="impOnDateSelection($event, 'from')"
            [maxDate]="minDate"
            [(ngModel)]="fromDate"
          />
          <button
            class="btn btn-outline-secondary bi bi-calendar3"
            (click)="d1.toggle()"
            type="button"
          ></button>
        </div>
      </div>
      <div class="col-12">
        <div class="input-group">
          <input
            class="form-control"
            placeholder="yyyy-mm-dd"
            name="dp"
            ngbDatepicker
            #d2="ngbDatepicker"
            (dateSelect)="impOnDateSelection($event, 'to')"
            [maxDate]="minDate"
            [(ngModel)]="toDate"
          />
          <button
            class="btn btn-outline-secondary bi bi-calendar3"
            (click)="d2.toggle();"
            type="button"
          ></button>
        </div>
      </div>
    </div>
    
    toDate: NgbDateStruct;
    fromDate: NgbDateStruct;
    
    impOnDateSelection(value, flag) {
      if (flag === 'from') {
        this.toDate = {
          year: 0,
          month: 0,
          day: 0,
        };
      }
    }