4

I implemented a really simple form to choose a range of time as the one in the code below:

<form [formGroup]="editEventForm" (ngSubmit)="c(onSubmitUpdate())">
  <div class="form-group bottom-form-details">
    <div class="row">
      <div class="col-sm-6">
        <label class="labels-status-form">Start Time</label>
      </div>
      <div class="col-sm-6">
        <ngb-timepicker [(ngModel)]="startTime" formControlName="startTime"></ngb-timepicker>
      </div>
    </div>
  </div>
  <div class="form-group bottom-form-details">
    <div class="row">
      <div class="col-sm-6">
        <label class="labels-status-form">End Time</label>
      </div>
      <div class="col-sm-6">
        <ngb-timepicker [(ngModel)]="endTime" formControlName="endTime"></ngb-timepicker>
      </div>
    </div>
  </div>
  <div class="modal-footer">
    <button type="submit" class="btn btn-primary btn-5">Update</button>
    <button type="button" class="btn btn-outline-dark" (click)="c('Close click')">Close</button>
  </div>
</form>

The models startTime and endTime just get the current hour and the current minute.

Once I set the start time(hour and minutes) through ngb-timepicker I would like to set end time from the start time. i.e. if I set 05:30 as start time I would like to set end time from 05:31.

ngb-datepicker provides a [minDate] but it is not the case with ngb-timepicker. Is there any way to do that in Angular 4?

Thanks in advance.

Carlito
  • 166
  • 3
  • 7

1 Answers1

0

It's possible to do that with an validation. You should use [formControl]

Template :

<ngb-timepicker [(ngModel)]="endTime" formControlName="endTime" [formControl]="ctrl"></ngb-timepicker
      <div *ngIf="ctrl.valid" class="small form-text text-success">Great choice</div>
      <div class="small form-text text-danger" *ngIf="!ctrl.valid">
        <div *ngIf="ctrl.errors['required']">Select some time during lunchtime</div>
        <div *ngIf="ctrl.errors['tooLate']">Oh no, it's way too late</div>
        <div *ngIf="ctrl.errors['tooEarly']">It's a bit too early</div>
      </div>

Typescript :

  ctrl = new FormControl('', (control: FormControl) => {
    const value = control.value;

    if (!value) {
      return null;
    }

    if (value.hour < 12) {
      return {tooEarly: true};
    }
    if (value.hour > 13) {
      return {tooLate: true};
    }

    return null;
  });
}
Pterrat
  • 1,682
  • 11
  • 18
  • A validation only check the values, Be Carefull! you're using a extrange mix between TemplateDrive Form (you use NgModel) and ReactiveForm (you use formControlName)! – Eliseo Feb 14 '18 at 14:26