Skip to content
Snippets Groups Projects
form-element-component.directive.ts 1.17 KiB
Newer Older
  • Learn to ignore specific revisions
  • import { Directive, OnInit } from '@angular/core';
    
    import { FormControl, FormGroup } from '@angular/forms';
    
    import { pairwise, startWith } from 'rxjs/operators';
    
    rhenck's avatar
    rhenck committed
    import { UnitUIElement } from './unit';
    
    import { FormService } from './form.service';
    
    export abstract class FormElementComponent implements OnInit {
    
    jojohoch's avatar
    jojohoch committed
      elementModel!: UnitUIElement;
    
      parentForm!: FormGroup;
    
      formControl: FormControl = new FormControl();
    
      constructor(private formService: FormService) { }
    
    rhenck's avatar
    rhenck committed
      ngOnInit(): void {
    
        this.formService.registerFormControl(this.elementModel.id);
    
        this.formControl = this.getFormControl(this.elementModel.id);
    
        this.formControl.valueChanges
          .pipe(startWith(null), pairwise())
          .subscribe(
            ([prevValue, nextValue] : [unknown, unknown]) => this.onValueChange([prevValue, nextValue])
          );
    
    rhenck's avatar
    rhenck committed
      private getFormControl(id: string): FormControl {
    
        // workaround for editor
    
        return (this.parentForm) ? this.parentForm.controls[id] as FormControl : new FormControl();
      }
    
    
      private onValueChange(values: [unknown, unknown]): void {
    
        const element = this.elementModel.id;
    
        this.formService.changeElementValue({ element, values });