How to use MutationObserver in Angular

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[]) => {

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.


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';

  selector: 'app-root',
  template: `
  <button (click)='onclick()'>Button</button>
      <h2><a target="_blank" href="" id="sample">リンク</a></h2>
  styleUrls: ['./app.component.css']
export class AppComponent implements OnInit,OnDestroy{
  public mo = new MutationObserver((mr:MutationRecord[]) =>{

  private target:any;
  ngOnInit() { = document.getElementById('sample');
    const opt:MutationObserverInit = {
      attributes: true,
    };,opt); // Monitor href here

  onclick(){ = ''; // Change the href

    if({; // End monitoring here

It works as follows