Mohammed Sabbah
Mohammed Sabbah

Reputation: 883

How to use RxJS in angular2?

Is there any way to write a code like that in angular 2?

var closeButton1 = document.querySelector('.close1');
var close1ClickStream = Rx.Observable.fromEvent(closeButton1, 'click');

I have tried many ways to put them in angular 2 component put it does not worked well! I tried something like this

component.ts

@ViewChild('delete') closeButton1: ElementRef;

close1ClickStream = Observable.fromEvent(closeButton1, 'click');

component.html

<!-- this code is inside *ngFor -->
<li><a #delete [routerLink]="['/update', item.id]">delete</a></li>

The problem is that I can not access the element even if I used AfterContentInit. Moreover, if I could access it, can I use the Observable.fromEvent(...)?

Upvotes: 0

Views: 221

Answers (2)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37373

Yes you can do it :

import { Observable } from 'rxjs/Observable';
//...

@ViewChild('delete') closeButton1: ElementRef;

close1ClickStream = Observable.fromEvent(closeButton1, 'click');

Upvotes: 0

Ashot
Ashot

Reputation: 1300

Use directives to handle events

@Directive({
   selector: '[click-handler]'
})
export class ClickHandler {

   constructor(public elementRef: ElementRef,) {
   }

   @HostListener('click', ['$event'])
   onClick(e) {
     // do staff here 
   }
}

usage

 <button click-handler> click </button>

Anyway if you want to do it using Observables you will need elementRef.nativeElement which is available here , just implement OnInit method and you are good to go.

Upvotes: 1

Related Questions