import { Component, OnInit } from '@angular/core'; import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms'; import * as moment from 'moment'; @Component({ selector: 'app-durationpicker', templateUrl: './durationpicker.component.html', styleUrls: [ './durationpicker.component.scss' ], providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: DurationpickerComponent } ] }) export class DurationpickerComponent implements OnInit, ControlValueAccessor { days = new FormControl(); hours = new FormControl(); minutes = new FormControl(); duration: string; model: moment.Duration; onChange = (duration) => { }; onTouched = () => { }; isDisabled = false; constructor() { } ngOnInit(): void { this.days.valueChanges.subscribe({ next: (value) => { if (value < this.model.days()) { this.model.subtract((this.model.days() - value), "days"); } else { this.model.add((value - this.model.days()), "days"); } this.checkValue(); } }) this.hours.valueChanges.subscribe({ next: (value) => { if (value < this.model.hours()) { this.model.subtract((this.model.hours() - value), "hours"); } else { this.model.add((value - this.model.hours()), "hours"); } this.checkValue(); } }) this.minutes.valueChanges.subscribe({ next: (value) => { if (value < this.model.minutes()) { this.model.subtract((this.model.minutes() - value), "minutes"); } else { this.model.add((value - this.model.minutes()), "minutes"); } this.checkValue(); } }) } checkValue() { if (this.model.asMinutes() <= 0) { this.days.setValue(0, { emitEvent: false }); this.hours.setValue(0, { emitEvent: false }); this.minutes.setValue(0, { emitEvent: false }); this.duration = null; } else { this.duration = this.model.toISOString(); } this.onChange(this.duration); this.onTouched(); } writeValue(duration: string): void { this.duration = duration; this.model = moment.duration(this.duration); this.days.setValue(this.model.days(), { emitEvent: false }); this.hours.setValue(this.model.hours()), { emitEvent: false }; this.minutes.setValue(this.model.minutes(), { emitEvent: false }); this.onTouched(); } registerOnChange(onChange: any): void { this.onChange = onChange; } registerOnTouched(onTouched: any): void { this.onTouched = onTouched; } setDisabledState?(isDisabled: boolean): void { this.isDisabled = isDisabled; } }