How to use MutationObserver in Angular
This is a note because I forget how to use MutationObserver.
It has one argument, a callback function. This callback function is executed when the DOM is modified.
The arguments of the callback function are as follows
- The first argument is a MutationRecord[] (optional)
- The second argument is MutationObserver (optional)
The following is an example of MutationObserver instance creation.
const mo = new MutationObserver((mr:MutationRecord[]) => { console.log(mr.length); });
This instance has an observe() method, which performs DOM change detection.
The arguments of observe are as follows
- The first argument is the node you want to monitor
- The second argument is an option (reference site)
The type of changes the DOM makes can be specified optionally, for example, if attributes or styles change, it is possible to detect such changes.
There is a method called disconnect() that terminates the monitoring.
sample
In this sample, MutationObserver monitors and detects changes in the href attribute.
A button is placed, and the user clicks the button to change the href attribute.
It just checks to see if it is detected at that time.
import { Component,OnInit,OnDestroy } from '@angular/core'; @Component({ selector: 'app-root', template: ` <button (click)='onclick()'>Button</button> <ul> <li> <h2><a target="_blank" href="https://angular.io/tutorial" id="sample">リンク</a></h2> </li> </ul> `, styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit,OnDestroy{ public mo = new MutationObserver((mr:MutationRecord[]) =>{ alert(mr.length); console.log(mr); }); private target:any; ngOnInit() { this.target = document.getElementById('sample'); const opt:MutationObserverInit = { attributes: true, attributeFilter:['href'] }; this.mo.observe(this.target,opt); // Monitor href here } onclick(){ this.target.href = 'https://www.yahoo.co.jp/'; // Change the href } ngOnDestroy(){ if(this.mo){ this.mo.disconnect(); // End monitoring here } } }
It works as follows
コメント