import { BoxOverview } from './../../../interfaces/boxes'; import { Component, OnInit, Output, Input, EventEmitter, ViewChild } from '@angular/core'; import { FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'app-box-assignment', templateUrl: './box-assignment.component.html', styleUrls: ['./box-assignment.component.css'] }) export class BoxAssignmentComponent implements OnInit { @ViewChild('firstInput') firstInput; @Input('box') box: BoxOverview; @Input('focus') set focus(focus: String) { if (focus) { this.buildForm(); this.firstInput.nativeElement.focus(); } } @Output() public form; @Output() onSubmit = new EventEmitter(); private formErrors: Object; validationMessages = { patientId: { required: 'Patient ID is required.' }, startDatetime: { required: 'A start date is required.' }, alias: { required: 'Box alias is required.', maxLength: 'Box alias cannot be more than 20 characters long.' } }; private submit() { this.onSubmit.next(); } constructor(public fb: FormBuilder) { } ngOnInit() { this.buildForm(); } buildForm(): void { // fix for timezone in datetime-local input field: // remove timezone offset to get the current local time in the input const date = new Date(); date.setTime(date.getTime() - date.getTimezoneOffset() * 1000 * 60); const now = date.toISOString().slice(0, 16); this.form = this.fb.group({ patientId: ['', Validators.required], startDatetime: [now, Validators.required], endDatetime: [{value: '', disabled: true}], alias: [this.box ? this.box.box.alias : '', [Validators.required, Validators.maxLength(20)]] }); this.form.valueChanges .subscribe(data => this.onValueChanged(data)); // copy empty values, since there are no errors yet this.formErrors = Object.assign({}, this.form.value); this.onValueChanged(); } onValueChanged(data?: any) { if (!this.form) { return; } const form = this.form; for (const field in this.formErrors) { if (field === undefined) { continue; } // clear previous error message (if any) this.formErrors[field] = ''; const control = form.get(field); if (control && control.dirty && !control.valid) { const messages = this.validationMessages[field]; for (const key in control.errors) { if (key === undefined) { continue; } this.formErrors[field] += messages[key] + ' '; } } } } }