Leonardo Gusmão
Leonardo Gusmão

Reputation: 47

Listening to DOM changes

I would like to do something in angular, but I don't know if there is a way to use it.

For example:

I have a screen open in 2 tabs, on that screen there is a button, which if I click on it, it shows a div. Simple.

HTML

<div class="card-line" *ngIf="showDiv">
      <span>show div</span>
</div>

<button (click)="showDiv()">test</button>

app.ts

showDiv = false;

showDiv() {
    showDiv = true;
 }

I would like when I click this button, it would show the div both on the screen that I am on and when the screen is open on the other tab. Is it possible to do this in angular? With any way to hear this change on one tab and reflect on the other tab?

Upvotes: 1

Views: 235

Answers (2)

Chellappan வ
Chellappan வ

Reputation: 27363

You can use Broadcast Channel API

The Broadcast Channel API is a simple API that makes communicating between browsing contexts

Try this:

export class AppComponent {
  name = "Angular " + VERSION.major;
  _showDiv = false;

  // Connection to a broadcast channel
  bc = new BroadcastChannel("channel");

  constructor(private cdr: ChangeDetectorRef) {
    this.bc.onmessage = ev => {
      this._showDiv = ev.data.showDiv;
      this.cdr.detectChanges();
    };
  }

  showDiv() {
    this._showDiv = true;
    this.bc.postMessage({ showDiv: true });
  }
}

Working Example

Upvotes: 2

Yannick Beauchamp-H
Yannick Beauchamp-H

Reputation: 1671

You can use localStorage.

showDiv = false;

toggleDiv() {
  this.showDiv = !this.showDiv;
  localStorage.setItem('showDiv', this.showDiv ? 'true' : 'false');
}

@HostListener('window:storage', ['$event'])
handleStorageEvent(event: StorageEvent) {
  console.log(event);
  if (event.key === 'showDiv') {
    this.showDiv = event.newValue === 'true';
  }
}

Upvotes: 1

Related Questions