Skip to content

Commit

Permalink
feat: making auUse synchronous
Browse files Browse the repository at this point in the history
Now that angular/angular#50320 is fixed,
it should be possible to change any angular signal at any time.
  • Loading branch information
divdavem committed Nov 24, 2023
1 parent 3fd0f2e commit 7fa4ce8
Showing 1 changed file with 5 additions and 16 deletions.
21 changes: 5 additions & 16 deletions angular/headless/src/lib/use.directive.ts
@@ -1,44 +1,33 @@
import type {Directive as AgnosUIDirective} from '@agnos-ui/core';
import type {OnChanges} from '@angular/core';
import {DestroyRef, Directive, ElementRef, inject, Input} from '@angular/core';
import type {Directive as AgnosUIDirective} from '@agnos-ui/core';

// All calls of the directive in this class are done asynchronously (with await 0)
// in order to avoid ExpressionChangedAfterItHasBeenCheckedError
// or the corresponding issue with signals (https://github.com/angular/angular/issues/50320)
// This is relevant especially if calling the directive changes variables used in a template.

export const useDirectiveForHost = <T>(use?: AgnosUIDirective<T>, params?: T) => {
const ref = inject(ElementRef);

let instance = use?.(ref.nativeElement, params as T);

async function destroyDirectiveInstance() {
function destroyDirectiveInstance() {
const oldInstance = instance;
instance = undefined;
use = undefined;
if (oldInstance?.destroy) {
await 0;
oldInstance.destroy?.();
}
}

inject(DestroyRef).onDestroy(destroyDirectiveInstance);

async function update(newUse?: AgnosUIDirective<T>, newParams?: T) {
function update(newUse?: AgnosUIDirective<T>, newParams?: T) {
if (newUse !== use) {
destroyDirectiveInstance();
use = newUse;
params = newParams;
if (newUse) {
await 0;
// checks that the directive did not change while waiting:
if (use === newUse && !instance) {
instance = use(ref.nativeElement, params as T);
}
if (use) {
instance = use(ref.nativeElement, params as T);
}
} else if (newParams != params) {
params = newParams;
await 0;
instance?.update?.(params as T);
}
}
Expand Down

0 comments on commit 7fa4ce8

Please sign in to comment.