监听 DOM 变化

时间:2021-02-16 01:42:53

标签: angular typescript frontend

想用angular做点什么,不知道有没有办法使用。

例如:

我在 2 个选项卡中打开了一个屏幕,在该屏幕上有一个按钮,如果我点击它,它会显示一个 div。简单。

HTML

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

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

app.ts

showDiv = false;

showDiv() {
    showDiv = true;
 }

我希望当我单击此按钮时,它会在我所在的屏幕上以及在另一个选项卡上打开屏幕时显示 div。有没有可能以角度来做到这一点?有什么办法可以在一个标签上听到这个变化并在另一个标签上反映?

2 个答案:

答案 0 :(得分:2)

您可以使用Broadcast Channel API

<块引用>

广播频道 API 是一个简单的 API,它使通信 浏览上下文之间

试试这个:

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

答案 1 :(得分:1)

您可以使用 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';
  }
}
相关问题