Skip to content

Commit

Permalink
feat: sync on touched change with parent layout #353
Browse files Browse the repository at this point in the history
  • Loading branch information
ZurabDev committed Oct 9, 2023
1 parent e49f402 commit a80e396
Showing 1 changed file with 25 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChangeDetectorRef, Directive, Injector, OnInit } from '@angular/core';
import { ChangeDetectorRef, Directive, DoCheck, Injector, OnInit } from '@angular/core';
import { AbstractControl, ControlValueAccessor, NgControl, NgModel, Validators } from '@angular/forms';
import { PrizmInputControl } from './input-control.class';
import { PrizmDestroyService } from '@prizm-ui/helpers';
Expand All @@ -11,14 +11,17 @@ import { PRIZM_EMPTY_FUNCTION } from '@prizm-ui/core';
@Directive()
export abstract class PrizmInputNgControl<T>
extends PrizmInputControl<T>
implements OnInit, ControlValueAccessor
implements OnInit, ControlValueAccessor, DoCheck
{
readonly destroy$!: PrizmDestroyService;
ngControl!: NgControl;
readonly changeDetectorRef!: ChangeDetectorRef;
readonly layoutComponent!: PrizmInputLayoutComponent;
private previousInternalValue$$ = new BehaviorSubject<T | null>(null);

private lastState = {
touched: false,
pristine: true,
};
onChange: (val: T) => void = PRIZM_EMPTY_FUNCTION;
onTouch: (val: T) => void = PRIZM_EMPTY_FUNCTION;
onTouched = PRIZM_EMPTY_FUNCTION;
Expand Down Expand Up @@ -132,7 +135,9 @@ export abstract class PrizmInputNgControl<T>
}

public registerOnTouched(fn: any) {
this.onTouch = fn;
this.onTouch = () => {
fn();
};
}

public writeValue(value: T): void {
Expand All @@ -142,6 +147,7 @@ export abstract class PrizmInputNgControl<T>
: value;

this.refreshLocalValue(this.fromControlValue(controlValue));
// sync on change
this.stateChanges.next();
}

Expand Down Expand Up @@ -202,4 +208,19 @@ export abstract class PrizmInputNgControl<T>
public markAsDirty(): void {
this.ngControl.control?.markAsDirty();
}

ngDoCheck(): void {
this.updateLayoutOnTouched();
}

private updateLayoutOnTouched(): void {
if (this.ngControl.pristine !== this.lastState.pristine) {
this.lastState.pristine = !!this.ngControl.pristine;
this.stateChanges.next();
}
if (this.ngControl.touched !== this.lastState.touched) {
this.lastState.touched = !!this.ngControl.touched;
this.stateChanges.next();
}
}
}

0 comments on commit a80e396

Please sign in to comment.