Если я вас правильно понял, вы хотите наблюдать за изменениями в DOM и изменять переменную, тогда вы можете использовать Subject.next ()
Subject.next (): метод subject next используется для отправки сообщений наблюдаемой, которые затем отправляются всем угловым компонентам, которые являются подписчиками этой наблюдаемой.
Шаги для достижения этой цели
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();
}
}
наслаждайтесь кодированием:)