Search code examples
angularangular2-observables

angular2 bind events to observable object


I am try to bind key up event and observable object, each time press a key in textbox field, I want to log "you have pressed:"+key string in console, there isnt any error shown but also nothing occurs when pressing keys..

 /// <reference path="../../../typings/tsd.d.ts" />
import { Component } from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
    moduleId:module.id,
    selector: 'search-samp',
    template: '<input id="search" type="text" class="form-control" placeholder="search">'
})
export class SearchComponent {
    constructor(){
         var keyups = Observable.fromEvent($("#search"), "keyup").map(e=> {e.target.value});
         keyups.subscribe(data => { 
             debugger
             console.log("you have pressed:"+data)});
    }
 }

Why its not working ?

EDITED:

 var keyups = Observable.fromEvent($("#search"), "keyup").map(function(e){debugger});

cant reach debugger point inside map function..it looks event never binded properly.. but why ?


Solution

  • 1) You should wait until ngAfterViewInit is called (there are no template's elements in DOM yet)

    2) You have to change the code of the map function either

    .map(e => { return e.target.value; })
    

    or

    .map(e => e.target.value)
    

    Plunker Example