Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //html
- <div class="container">
- <form [formGroup]="shift">
- <div class="form-group">
- <div class="label">Shift starts at</div>
- <div class="time-wrapper">
- <input class="input" type="time" formControlName="shiftStart" />
- <i class="material-icons time-icon">
- access_time
- </i>
- </div>
- </div>
- <div class="form-group">
- <div class="label">Shift ends at</div>
- <div class="time-wrapper">
- <input class="input" type="time" formControlName="shiftEnd" />
- <i class="material-icons time-icon">
- access_time
- </i>
- </div>
- </div>
- </form>
- </div>
- //ts
- import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
- import { FormGroup, FormControl, Validators } from '@angular/forms';
- @Component({
- selector: 'app-employee',
- templateUrl: './employee.component.html',
- styleUrls: ['./employee.component.css'],
- changeDetection: ChangeDetectionStrategy.OnPush,
- })
- export class EmployeeComponent {
- shift = new FormGroup(
- {
- shiftStart: new FormControl('', [Validators.required]),
- shiftEnd: new FormControl('', [Validators.required]),
- },
- this.validateShiftStartEnd.bind(this),
- );
- get shiftStart() {
- return this.shift.get('shiftStart');
- }
- get shiftEnd() {
- return this.shift.get('shiftEnd');
- }
- constructor() {}
- toMs(h:number, m:number):number {
- return ((h*60*60+m*60)*1000);
- }
- validateShiftStartEnd(group: FormGroup) {
- const start = group.controls.shiftStart.value;
- const end = group.controls.shiftEnd.value;
- const startH = +start.split(':')[0];
- const startM = +start.split(':')[1];
- console.log('this', this);
- const startInMs = this.toMs(startH, startM);
- const endH = +end.split(':')[0];
- const endM = +end.split(':')[1];
- const endInMs = this.toMs(endH, endM);
- // console.log('startInMs', startInMs)
- // console.log('endInMs', endInMs);
- // const startHH = start.split(':')[0] * 60;
- // const startMin = +start.split(':')[1];
- // const totalStartMinutes = startHH + startMin;
- // const endHH = end.split(':')[0] * 60;
- // const endMin = +start.split(':')[1];
- // const totalEndMinutes = endHH + endMin;
- if (!startInMs && !endInMs) {
- return;
- }
- if (startInMs > endInMs) {
- group.controls.shiftStart.setErrors({ startGreaterThanEnd: true });
- group.controls.shiftEnd.setErrors({ startGreaterThanEnd: true });
- return {
- startGreaterThanEnd: true,
- };
- }
- if (endInMs > startInMs) {
- group.controls.shiftStart.setErrors(null);
- group.controls.shiftEnd.setErrors(null);
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement