首页 > 解决方案 > Angular:使用可观察对象检测 DOM 中的变化

问题描述

我正在尝试读取我的角度组件的 DOM 变化。

我正在使用 observables 将该更改检索到 typescript 变量中(不确定这是否是正确的方法)。这是我实现它的方式:

app.component.html

<input type="text" name="refl" [(ngModel)]="txt">
<app-test>
    <div class="t1">
        The text : {{txt}}
    </div>
</app-test>

test.component.html

<div #t><ng-content select=".t1"></ng-content></div>
Received Text : {{text}}

测试组件.ts

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: [ './test.component.scss' ]
})
export class TestComponent implements AfterContentInit {

  @ViewChild('t') private tq: ElementRef;
  private text: string = null;
  constructor () {}

  ngAfterViewInit() {

    new Observable(obs => {obs.next(this.tq.nativeElement.innerText);})
    .subscribe((dt: string) => { this.text = dt; });
  }
}

我的理解是,由于我使用 observable 来监视 DOM 中的变化,因此我会反映到{{text}}test.component.html 中。

但我在那个地方什么也没收到。

这是使用角度观察 DOM 变化的正确方法吗?

标签: angularangular2-observables

解决方案


如果我理解正确,您想观察 DOM 中的变化并更改变量,那么您可以使用 Subject.next()

Subject.next():Subject next 方法用于向 observable 发送消息,然后将这些消息发送到作为该 observable 订阅者的所有 angular 组件。

实现这一目标的步骤

1)制作服务MyService.Service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MyService {
   private subject = new Subject<any>();

   UpdateText(message: string) {
      this.subject.next({ text: message });
   }

    clearText() {
      this.subject.next();
   }

    getText(): Observable<any> {
       return this.subject.asObservable();
    }
}

2) app.component.html

<input type="text" name="refl" [(ngModel)]="txt" (keyUp)="ChangeText()">

3)app.component.ts

import {myService} from './myservice.ts';
@Component({
  selector: 'app',
  templateUrl: './test.component.html',
  styleUrls: [ './test.component.scss' ]
 })
 export class AppComponent {
 txt: any;
 constructor (private myServiceObj: myService) {}

 ChangeText(){
   this.myServiceObj.UpdateText(txt);
 }
}

4) test.component.html

Received Text : {{text}}

5)test.component.ts

import {myService} from '../myservice.ts';
@Component({
 selector: 'app-test',
 templateUrl: './test.component.html',
 styleUrls: [ './test.component.scss' ]
 })
export class TestComponent {

 private text: string = null;
 subscription: Subscription;

 constructor (private myServiceObj: myService) {
  this.subscription = this.myServiceObj.getText().subscribe(text => { 
  this.text = text; });
  }

  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }  
}

享受编码:)


推荐阅读