angular 2 observable , subscribe not working

I am doing basic test of angular observable to observe keyup of a textbox, i am not getting any error but subscribe is not working in this, so nothing coming in console from it..

import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'appobserve',
    template: `
      <b>Angular 2 Component Using Observables!</b>

      > input id="search" type="text" name="search" class="form-control" >
    `
})
export class ObserveComponent {
  constructor() {
      console.log('startedbbb');
        var keyups = Observable.fromEvent($('#search'),'keyup');
        keyups.subscribe(function(ev) { console.log("click", ev) });
  }
}

Upvotes: 1

Views: 1383

Answers (2)

Obaid
Obaid

Reputation: 1445

In case you still want to use Observable on keyup of textbox:

import { Component, ViewChild } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';

@Component({
  selector: 'my-app',
  template: `<input #searchbox type="text" name="search" class="form-control">`
})
export class AppComponent { 
  @ViewChild('searchbox') searchbox;

  ngOnInit(){
    Observable.fromEvent(this.searchbox.nativeElement, 'keyup')
    .subscribe((event)=>console.log(event));
  }
}

Upvotes: 0

Poul Kruijt
Poul Kruijt

Reputation: 71961

This is angular2, with jquery, with javascript, with typescript, with rx.. and some strangely formatted html.

  • never use the keyword function inside a component/service/class, this will mess up the this context
  • no need for jQuery, just add an angular (keyup) listener on your input element
  • no need for observable, this is handled in the angular templating, which already uses observables (or actually EventEmitters which uses observables)

This will work:

@Component({
    selector: 'appobserve',
    template: `
      <b>Angular 2 Component Using Observables!</b>
      <input type="text" name="search" class="form-control" (keyup)="onKeyUp($event)">
    `
})
export class ObserveComponent {

   constructor() {}

   onKeyUp(event: KeyboardEvent): void {
       console.log(event);
   }
}

Upvotes: 7

Related Questions