【问题标题】:Angular 2: Observable from multiple Events or EventhandlerAngular 2:可从多个事件或事件处理程序中观察到
【发布时间】:2017-05-04 10:58:47
【问题描述】:

我在组件模板中对多个输入及其事件进行了分组,如下所示:

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

现在我想从onSearchObjectChange() 创建一个 Observable,它应该得到一个 Promise 的结果。我将如何做到这一点,或者有更好的方法来使用 Observable?我也可以对 Objects 使用distinctUntilChanged() 函数吗?

我试图用模板变量来解决它:

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

在 ViewChild 的帮助下:

@ViewChild('search') search;

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

但它不起作用......

【问题讨论】:

    标签: javascript angular typescript rxjs angular2-observables


    【解决方案1】:
    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!"))
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多