angular - 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 变化的正确方法吗?
解决方案
如果我理解正确,您想观察 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();
}
}
享受编码:)
推荐阅读
- asp.net-mvc - 如何在 Html.EditorFor 中使用 DefaultValueAttribute 值?
- python - 如何在python中动态地将2个不同的列表添加到字典中
- security - 用户名/密码可以作为一个字符串传递吗?
- python - 无法根据需要使用 python 以 json 格式写入
- android - ANT传输协议:发送Broadcast Messages后读取Parcel
- python - IndexError : 列表索引超出范围
- javascript - 使用全日历“事件作为函数”(在 Vue 中)并返回一个承诺在更新资源时不会填充事件?
- javascript - 为什么我得到 Promise 待处理而不是 Express 响应?
- java - 两个对话框 setAlwaysOnTop(true):第二个生成的对话框在第一个对话框后面
- android - Android - 从网站检查 Chrome 应用程序是否具有存储权限