Caleb Oki Caleb Oki - 1 year ago 233
HTML Question

Observable event not working in Angular2

I am trying to create a Keyup event in angular2, that is triggered when something is typed in the search box, the event is then logged in the console. owever nothing is displayed in the console. This is my app.component.ts file

/// <reference path="../typings/tsd.d.ts" />

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

selector: 'my-app',
template: `
<input id="search" type="text" class="form-control" placeholder="Search">

export class AppComponent {

var keyups = Observable.fromEvent($("#search"), "keyup");

keyups.subscribe(function(data) {


And my index.html file is

<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link rel="stylesheet" href="app/bootstrap.min.css">
<link rel="stylesheet" href="app/styles.css">

<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>

<script src="node_modules/rxjs/bundles/Rx.js"></script>

<script src=""></script>
<script src=""></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
System.import('app').catch(function(err){ console.error(err); });
<!-- 3. Display the application -->

Please could someone point out what I am missing here? Thanks

Answer Source

First, you can go about capturing key presses in another way:

<input (keyup)="onKeyPress()" id="search" type="text" class="form-control" placeholder="Search">

This binds the keyup event to running what you assign to that event binding. You can then add an onKeyPress function in your component with the console.log.!#event-binding

Another thing is that the constructor runs before the view is initialized. So if you insist on binding to events outside of the template, you can do this:

export class AppComponent implements AfterViewInit

And implement an ngAfterViewInit function in the component where you can use that Observable. Be sure to import AfterViewInit from @angular/core.