Search code examples
angulartimepickerng-bootstrap

Multiple ngb-timepicker in one form with Angular4


I am using Angular 4 to create a form with start time and end time, using two ngb-timepicker. When I set the model to both of them, the first one instantiates the values for the second one. Any idea on how to instantiate them separately? My HTML looks like this:

<ngb-timepicker [(ngModel)]="time1"></ngb-timepicker>
<ngb-timepicker [(ngModel)]="time2"></ngb-timepicker>

And my component:

import {Component} from '@angular/core';

@Component({
 selector: 'schedule-form',
 templateUrl: './schedule-form.component.html'
})

export class NgbdTimepickerBasic {
  time1 = {hour: startDateH, minute: startDateM};
  time2 = {hour: endDateH, minute: endDateM};
}

The result is that time1 will show time2, so only time2 is correct.


Solution

  • You need NgbTimeStruct to format the date which ngb-timepicker knows

    import {Component} from '@angular/core';
    import {NgbTimeStruct} from '@ng-bootstrap/ng-bootstrap';
    
    @Component({
     selector: 'schedule-form',
     templateUrl: './schedule-form.component.html'
    })
    
    export class NgbdTimepickerBasic {
      //declaration
      time1: NgbTimeStruct;
      time2: NgbTimeStruct;
    
      ngOnInit() {
        //get your start and end time and assign it to below 
        this.time1 = {hour: 13, minute: 30, second: 0};
        this.time2 = {hour: 16, minute: 15, second: 0};
      }
    
    }