Angular 2: Observable from multiple Events or Eventhandler

1.4k views Asked by At

I grouped multiple Inputs and their events in the component template like this:

<tr (input)="onSearchObjectChange($event)">
    <th><input [(ngModel)]="searchObject.prop1"></th>
    <th><input [(ngModel)]="searchObject.prop2"></th>
    ...
</tr>

Now I want to create an Observable out of the onSearchObjectChange(), which should get the result of an Promise. How would I do this or is there a better way to use an Observable? Can I use the distinctUntilChanged() function for Objects too?

I tried to solve it with a template variable:

<tr #search >
<th><input [(ngModel)]="searchObject.prop1"></th>
<th><input [(ngModel)]="searchObject.prop2"></th>
...
</tr>

And with the help of ViewChild:

@ViewChild('search') search;

ngAfterViewInit() {
    Observable.fromEvent(this.search, 'input')
        .subscribe(() => console.log("help"));
}

But it doesn't work...

1

There are 1 answers

0
JoCa On
import {Component, AfterViewInit, ViewChild, ElementRef} from '@angular/core';
import {Observable} from "rxjs";

@Component({
    selector: 'search',
    templateUrl: './search.html',
    styleUrls: ['./search.css'],
    providers: []
})
export class SearchComponent implements AfterViewInit {
@ViewChild('search') search: ElementRef;

constructor() {
}

ngAfterViewInit() {
    Observable.fromEvent(this.search.nativeElement, 'input')
        .subscribe(() => alert("It works!"))
}
}