Skip to content

Commit d892044

Browse files
committed
feat(template): add PLATFORM and effectOnceIf utilities
Introduced `effectOnceIf`, enabling conditional execution of effects in Angular's DI context with cleanup and flexible options. Added new `PLATFORM` token for platform-specific feature detection.
1 parent d614d4d commit d892044

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

  • libs/template/virtual-view/src/lib
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
2+
import { DOCUMENT, inject, InjectionToken, PLATFORM_ID } from '@angular/core';
3+
4+
export const PLATFORM = new InjectionToken('PLATFORM', {
5+
providedIn: 'platform',
6+
factory: () => {
7+
const platformId = inject(PLATFORM_ID);
8+
const document = inject(DOCUMENT);
9+
10+
const isServer = isPlatformServer(platformId);
11+
const isBrowser = isPlatformBrowser(platformId);
12+
const isServerRenderer = isBrowser && !!document.getElementById('ng-state');
13+
14+
return { isServer, isBrowser, isServerRenderer };
15+
},
16+
});
17+
18+
// https://ngxtension.dev/utilities/signals/effect-once-if/
19+
import {
20+
CreateEffectOptions,
21+
effect,
22+
EffectCleanupRegisterFn,
23+
EffectRef,
24+
runInInjectionContext,
25+
untracked,
26+
} from '@angular/core';
27+
import { assertInjector } from './assert-injector';
28+
29+
export function effectOnceIf<T = any>(
30+
condition: () => T,
31+
execution: (
32+
valueFromCondition: NonNullable<T>,
33+
onCleanup: EffectCleanupRegisterFn,
34+
) => void,
35+
options?: Omit<CreateEffectOptions, 'manualCleanup'>,
36+
): EffectRef {
37+
const assertedInjector = assertInjector(effectOnceIf, options?.injector);
38+
return runInInjectionContext(assertedInjector, () => {
39+
const effectRef = effect((onCleanup) => {
40+
const hasCondition = condition();
41+
if (hasCondition) {
42+
untracked(() => execution(hasCondition, onCleanup));
43+
effectRef.destroy();
44+
}
45+
}, options);
46+
return effectRef;
47+
});
48+
}
49+
50+
export type EffectOnceIfConditionFn<T> = Parameters<typeof effectOnceIf<T>>[0];
51+
export type EffectOnceIfExecutionFn<T> = Parameters<typeof effectOnceIf<T>>[1];
52+
export type EffectOnceIfOptions<T> = Parameters<typeof effectOnceIf<T>>[2];

0 commit comments

Comments
 (0)