Skip to content

[Feature] - interested in a classMutationSignal? #622

@sp90

Description

@sp90

I just wanted to know if you had any interest in a classMutationSignal that basically returns the current classes of the element passed to it.

Just before i start making all the tests for it etc

@Component({
  selector: 'sh-datepicker',
  imports: [],
  template: ``
})
export class ExampleComponent {
  #selfRef = inject(ElementRef);

  currentClassList = classMutationSignal(this.#selfRef.nativeElement);
  someEffect = effect(() => {
    const _ = this.currentClasses();
  
    // Some action on class change
  });
}
import { DestroyRef, inject, signal, Signal, WritableSignal } from '@angular/core';

export function classMutationSignal(element: HTMLElement): Signal<string> {
  const classListSignal: WritableSignal<string> = signal(element.className);
  const destroyRef = inject(DestroyRef);

  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
        const target = mutation.target as HTMLElement;
        classListSignal.set(target.className);
      }
    }
  });

  observer.observe(element, { attributes: true });
  destroyRef.onDestroy(() => observer.disconnect());

  return classListSignal.asReadonly();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions