Skip to content

Commit

Permalink
fix(Disabled): Apply the markDirty for disabled in the same side effe…
Browse files Browse the repository at this point in the history
…ct so it delays for the init phase.

Refactor with concat to make the flow clearer
  • Loading branch information
zakhenry committed Jun 24, 2021
1 parent c936ff7 commit f520b7f
Showing 1 changed file with 16 additions and 23 deletions.
39 changes: 16 additions & 23 deletions projects/ngx-sub-form/src/lib/ngx-sub-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import { ɵmarkDirty as markDirty } from '@angular/core';
import { FormControl } from '@angular/forms';
import isEqual from 'fast-deep-equal';
import { getObservableLifecycle } from 'ngx-observable-lifecycle';
import { combineLatest, EMPTY, forkJoin, identity, merge, Observable, of, timer } from 'rxjs';
import { combineLatest, concat, defer, EMPTY, forkJoin, identity, merge, Observable, of, timer } from 'rxjs';
import {
catchError,
delay,
exhaustMap,
filter,
finalize,
ignoreElements,
map,
mapTo,
shareReplay,
Expand Down Expand Up @@ -217,31 +220,21 @@ export function createForm<ControlInterface, FormInterface>(
formGroup.reset(value, { emitEvent: false });
}),
),
supportChangeDetectionStrategyOnPush:
// we need to wait first for the view to have been initialised
// otherwise calling `markDirty` previous to that throws an error
// `Cannot read property 'nodeIndex' of null`
// and the `delay(0)` doesn't give us that guarantee on its own
lifecyleHooks.afterViewInit.pipe(
exhaustMap(() =>
controlValue$.pipe(
delay(0),
tap(() =>
// support `changeDetection: ChangeDetectionStrategy.OnPush`
// on the component hosting a form
// fixes https://github.com/cloudnc/ngx-sub-form/issues/93
markDirty(componentInstance),
),
),
),
supportChangeDetectionStrategyOnPush: concat(
lifecyleHooks.afterViewInit.pipe(take(1)),
merge(controlValue$, setDisabledState$).pipe(
delay(0),
tap(() => {
// support `changeDetection: ChangeDetectionStrategy.OnPush`
// on the component hosting a form
// fixes https://github.com/cloudnc/ngx-sub-form/issues/93
markDirty(componentInstance);
}),
),
),
setDisabledState$: setDisabledState$.pipe(
tap((shouldDisable: boolean) => {
shouldDisable ? formGroup.disable({ emitEvent: false }) : formGroup.enable({ emitEvent: false });
// without emitting an event the form is not marked as dirty which can cause issues with the display not updating
// to indicate that form elements are disabled, especially with `changeDetection: ChangeDetectionStrategy.OnPush`
// @related https://github.com/cloudnc/ngx-sub-form/issues/143
markDirty(componentInstance);
}),
),
updateValue$: updateValueAndValidity$.pipe(
Expand All @@ -255,7 +248,7 @@ export function createForm<ControlInterface, FormInterface>(
),
};

forkJoin(sideEffects)
merge(...Object.values(sideEffects))
.pipe(takeUntil(lifecyleHooks.onDestroy))
.subscribe();

Expand Down

0 comments on commit f520b7f

Please sign in to comment.