From 72c0188e05255a45e3e4662904cbbeef47013738 Mon Sep 17 00:00:00 2001 From: Andrew Kushnir Date: Sun, 31 Jan 2021 22:22:09 -0800 Subject: [PATCH] refactor(forms): avoid duplicated code in `AbstractControlStatus` directive (#40651) This commit updates `AbstractControlStatus` directive code to remove duplicated logic in getters and replaces that logic with a new function that accepts an argument. PR Close #40651 --- .../forms/src/directives/ng_control_status.ts | 38 ++++++------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/packages/forms/src/directives/ng_control_status.ts b/packages/forms/src/directives/ng_control_status.ts index 41aad8646d..a032484823 100644 --- a/packages/forms/src/directives/ng_control_status.ts +++ b/packages/forms/src/directives/ng_control_status.ts @@ -12,6 +12,8 @@ import {AbstractControlDirective} from './abstract_control_directive'; import {ControlContainer} from './control_container'; import {NgControl} from './ng_control'; +type AnyControlStatus = 'untouched'|'touched'|'pristine'|'dirty'|'valid'|'invalid'|'pending'; + export class AbstractControlStatus { private _cd: AbstractControlDirective|null; @@ -19,37 +21,19 @@ export class AbstractControlStatus { this._cd = cd; } - get ngClassUntouched(): boolean { - return this._cd?.control?.untouched ?? false; - } - get ngClassTouched(): boolean { - return this._cd?.control?.touched ?? false; - } - get ngClassPristine(): boolean { - return this._cd?.control?.pristine ?? false; - } - get ngClassDirty(): boolean { - return this._cd?.control?.dirty ?? false; - } - get ngClassValid(): boolean { - return this._cd?.control?.valid ?? false; - } - get ngClassInvalid(): boolean { - return this._cd?.control?.invalid ?? false; - } - get ngClassPending(): boolean { - return this._cd?.control?.pending ?? false; + is(status: AnyControlStatus): boolean { + return !!this._cd?.control?.[status]; } } export const ngControlStatusHost = { - '[class.ng-untouched]': 'ngClassUntouched', - '[class.ng-touched]': 'ngClassTouched', - '[class.ng-pristine]': 'ngClassPristine', - '[class.ng-dirty]': 'ngClassDirty', - '[class.ng-valid]': 'ngClassValid', - '[class.ng-invalid]': 'ngClassInvalid', - '[class.ng-pending]': 'ngClassPending', + '[class.ng-untouched]': 'is("untouched")', + '[class.ng-touched]': 'is("touched")', + '[class.ng-pristine]': 'is("pristine")', + '[class.ng-dirty]': 'is("dirty")', + '[class.ng-valid]': 'is("valid")', + '[class.ng-invalid]': 'is("invalid")', + '[class.ng-pending]': 'is("pending")', }; /**