Hello!
Given a change in the content of a container (string signal), I need to determine whether I should show something or not (boolean signal).
I can only determine whether to toggle the boolean signal based on an attribute of the container element (let's say it's a given scrollWidth )
So, I tried using:
// ...Template is <span #container>{{ content() }}</span>
readonly elementRef = viewChild<ElementRef<HTMLSpanElement>>('container');
readonly content = this.contentService.content; // Signal that can change
But if I use a computed for the boolean signal, I noticed that the elementRef used does not change when its width change (because content() changed for example).
So, I need to use a ResizeObserver to detect this, and it does. That's good.
I can have an effect that depends on the elementRef(), and disconnects on return. All good.
// Note! This effect does not run when the content of the span (content signal) changes. We would need to also add that dependency to this effect to trigger the check one the name changes...
effect(() => {
const element = this.elementRef()?.nativeElement;
if (!element) return;
const observer = new ResizeObserver((entry) => {
const el = entry[0].target;
// Here I can check whether the element's size should update the boolean signal.
this.booleanSignal.set(el.scrollWidth > VALUE);
});
observer.observe(element.nativeElement);
return () => observer.disconnect();
});
But then it hit me: We are not supposed to update signals inside an effect (https://angular.dev/guide/signals#use-cases-for-effects).
Then how could this be achieved with a computed? Can it be achieved with it at all?
Is there a way to use the ResizeObserver as a signal itself?
Feels like I'm missing a piece of this puzzle. Let me know what do you think!
EDIT: The code here was written by myself here on DIscord as an example. Will update if there are glaring errors.