Angular -2 Observable Doesn't Work

The following code should log data from the keyup event taken from the input field, but nothing happens, and the console remains empty (no errors).

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

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

@Component({
    selector: 'my-app',
    template: `
        <input id="search" type="text" class="form-control">
    `
})
export class AppComponent {
    constructor(){
        var keyups = Observable.fromEvent($("#search"), "keyup");
        keyups.subscribe(data => console.log(data));
    }
}
+4
source share
3 answers

You have a couple of problems with your code.

1). Observable.fromEventexpects the HTML element to become the first parameter, however you are passing a jQuery instance.

2). You are trying to subscribe to a constructor that does not guarantee that the contents of the component will be loaded by this time.

3). You are using a hardcoded CSS selector #search, which you should never do.

Now you can fix it:

  • Set the template link to the input field.

  • Observable.fromEvent ngAfterContentInit hook:

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

  @ViewChild('search') input: ElementRef

  ngAfterContentInit() {
    var keyups = Observable.fromEvent(this.input.nativeElement, "keyup");
    keyups.subscribe(data => console.log(data));
  }
}

: http://plnkr.co/edit/5TFDv0OoV8wWnDYneiFD?p=preview

+5

Rxjs, angular2?

//our root app component
import {Component, Pipe,ViewChild} from '@angular/core';
import {myservice} from 'app/service';

@Component({
  selector: 'my-app',
  template: `
          <h1>angular2</h1>
            <input #box (keyup)="onKey(box.value,$event)">
    <p>{{values}}</p>
  `,
})
export class AppComponent {       
  values = '';

  onKey(value: string,event) {
    this.values += value + ' | ';
    console.log(event);
  }
}

https://plnkr.co/edit/ZSqLNhSi0lI4HdKhulBf?p=preview

: https://angular.io/docs/ts/latest/guide/user-input.html

0

, jquerySelector, @ViewChild . : #search .

import { AfterViewInit, Component, ViewChild, ElementRef } from '@angular/core';
import { Observable } from 'rxjs/Rx'
@Component({
selector: 'my-app',
template:`
    <input #search type="text" class="form-control"  >
`
})
export class AppComponent {

@ViewChild('search') input: ElementRef

ngAfterContentInit() {
    var keyups = Observable.fromEvent(this.input.nativeElement, "keyup");
    keyups.subscribe(data => console.log(data));
}  
0

Source: https://habr.com/ru/post/1648134/


All Articles