Created
October 28, 2024 09:16
-
-
Save Armenvardanyan95/b89f1087c76231238816c576e3a985fb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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