Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target an HTML element using rxjs fromEvent in Angular 6

Issue

I have used ngrx fromEvent operator to create an Observable from 2 input text fields, I have used document as target which is fine, but now I want to target only one input field. I am not sure sure what to use instead of document to target only one input field.

What I have done so far to get the target

  • Used document.getElementByID('someID')
  • Used ElementRef
  • Used document.querySelector('someID')

Code

StackBlits live editor

import { Component } from '@angular/core';
import { fromEvent } from 'rxjs';

@Component({
  selector: 'my-app',
  template: `<input type="text">
             <input type="text">`
})
export class AppComponent {
  ngOnInit() {
    fromEvent(document, 'keyup')
      .subscribe(res => console.log(res.target.value));
  }
}

Thanks for your help in advance.

like image 454
Dhiru Avatar asked Sep 05 '18 10:09

Dhiru


People also ask

What is FromEvent in RxJs?

FromEvent: FromEvent is a method provided by RxJs to create Observable. The best thing is that we can create Observable from DOM events directly. By DOM events, it means click event, key up events, scroll events, etc. that is a simple mouse click, we can create a stream of data, i.e. an Observable.

Which of the following will create an observable from an event using RxJs in angular 6?

Angular provides FromEvent method to create an observable from DOM events directly.


1 Answers

You can give the input field that you want to observe, a template variable.

You can use then use @ViewChild to get access to that input. And then use the nativeElement property on it.

Now the nativeElement property will only be accessible after the view has initialized. So you can use the AfterViewInit Component Lifecycle Hook in order to access it.

import { Component, ViewChild, ElementRef } from '@angular/core';
import { fromEvent } from 'rxjs';

@Component({
  selector: 'my-app',
  template: `<input #toTarget type="text">
             <input type="text">`
})
export class AppComponent {

  @ViewChild('toTarget') toTarget: ElementRef;

  ngAfterViewInit() {
    fromEvent(this.toTarget.nativeElement, 'keyup')
      .subscribe(res => console.log(res.target.value));
  }
}

Here's an Updated StackBlitz for your ref.

like image 194
SiddAjmera Avatar answered Oct 05 '22 19:10

SiddAjmera