Skip to content

Instantly share code, notes, and snippets.

@Armenvardanyan95
Created October 28, 2024 09:16
Show Gist options
  • Save Armenvardanyan95/b89f1087c76231238816c576e3a985fb to your computer and use it in GitHub Desktop.
Save Armenvardanyan95/b89f1087c76231238816c576e3a985fb to your computer and use it in GitHub Desktop.
@Component({
template: `
<h1 #heading>Mutation {{text()}}</h1>
<input type="text" [(ngModel)]="text">
@if(mutations$) {
<span>{{ mutations$ | async }}</span>
}
`,
})
export class MutationComponent implements AfterViewInit {
text = signal('');
heading = viewChild.required<ElementRef<HTMLHeadingElement>>('heading');
mutations$?: Observable<string>;
ngAfterViewInit(): void {
let observer: MutationObserver;
this.mutations$ = fromEventPattern<MutationRecord[][]>(
// create the observer and observe the element
// when the Observable is subscribed to
(handler) => {
observer = new MutationObserver(handler);
observer.observe(this.heading().nativeElement, {
subtree: true,
characterData: true,
characterDataOldValue: true,
});
},
// disconnect when unsubscribed
() => observer.disconnect(),
).pipe(
map(([[mutations]]) => mutations.oldValue ?? ''),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment