service-check-form.component.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { Component, ElementRef, Input, OnInit, QueryList, ViewChildren } from '@angular/core';
  2. import { FormControl, FormGroup, FormArray, FormBuilder } from '@angular/forms';
  3. import { faMinusSquare, faPlusSquare } from '@fortawesome/free-solid-svg-icons';
  4. import { ServiceApiService } from '../../services/service-api.service';
  5. import { deepCopy } from '../../../../../common/util/object-utils';
  6. @Component({
  7. selector: 'app-service-check-form',
  8. templateUrl: './service-check-form.component.html',
  9. styleUrls: ['./service-check-form.component.scss']
  10. })
  11. export class ServiceCheckFormComponent implements OnInit {
  12. @ViewChildren('checkInput')
  13. set checkRows(childs: QueryList<ElementRef<HTMLInputElement>>) {
  14. if (childs?.length && childs.get(0)?.nativeElement.value === '') {
  15. //new added children via addPattern without value gets focus
  16. childs.get(0)?.nativeElement.focus();
  17. }
  18. }
  19. @Input()
  20. serviceCheck!: HttpCheckConfig;
  21. public fa = { plus: faPlusSquare, delete: faMinusSquare };
  22. serviceCheckForm: FormGroup = this.formBuilder.group({
  23. id: -1, //constant for defaultValues
  24. title: '', //constant for defaultValues
  25. active: undefined, //constant for defaultValues
  26. url: '', //constant for defaultValues
  27. interval: 10, //constant for defaultValues
  28. timeout: 10, //constant for defaultValuess
  29. checks: this.formBuilder.array([]),
  30. notify: true,
  31. notifyThreshold: 3
  32. });
  33. constructor(private formBuilder: FormBuilder, private serviceApi: ServiceApiService) {}
  34. get checks(): FormArray {
  35. return this.serviceCheckForm.controls['checks'] as FormArray;
  36. }
  37. ngOnInit(): void {
  38. this.patchForm(this.serviceCheck);
  39. }
  40. private patchForm(serviceCheck: HttpCheckConfig) {
  41. this.checks.controls = [];
  42. serviceCheck.checks.reverse().forEach(e => {
  43. this.checks.controls.push(new FormControl(e));
  44. });
  45. this.serviceCheckForm.patchValue(serviceCheck);
  46. }
  47. addPattern() {
  48. this.checks.controls.unshift(new FormControl(''));
  49. //focus set via viewChildren setter, here is too early
  50. }
  51. removePattern(index: number) {
  52. this.checks.controls.splice(index, 1);
  53. }
  54. async save() {
  55. try {
  56. this.serviceCheckForm.updateValueAndValidity();
  57. const copy = deepCopy(this.serviceCheckForm.value as HttpCheckConfig);
  58. copy.checks = this.checks.controls.map(e => e.value).reverse();
  59. const savedCheck = await this.serviceApi.saveServiceCheck(this.serviceCheck.serverId as number, copy);
  60. this.patchForm(savedCheck);
  61. } catch (error: any) {
  62. console.error(error);
  63. }
  64. }
  65. }