簡體   English   中英

可從<button>Angular2 中的點擊事件中觀察到</button>

[英]Observable from <button> click event in Angular2

使用 Angular 2 從按鈕的 onclick 事件創建 observable 的首選方法是什么?

我不確定從組件代碼中的 DOM 中獲取本機元素是否被認為是最佳實踐(我該怎么做?),或者是否還有其他一些我不知道的快捷方式。

不要想太多。

@ViewChild('button') button;
clicks$:Observable<any>;

ngOnInit() {
  this.clicks$ = Observable.fromEvent(this.button.nativeElement, 'click');
}

您可以像Angular2 RxJS 中解釋的那樣使用Observable.fromEvent 獲取 'Observable_1.Observable.fromEvent is not a function' 錯誤

或者只是轉發到一個可觀察的像

private obs = new Subject();
public obs$ = this.obs.asObservable();

@HostListener('click', ['$event']) 
clickHandler(event){
  this.obs.next(event);
}

<button (click)="obs.next($event)">

@Gunter 的示例對我來說不太適用,因為我的編譯器無法識別publ

這是一個對我modal.component.ts的例子: modal.component.ts

import { Output, Component } from '@angular/core';
import {Subject} from "rxjs/Subject";

export class MyModal{

    private clickStream = new Subject<Event>();

    @Output() observ = this.clickStream.asObservable();

    buttonClick(event:Event){
        this.clickStream.next(event);
    }
}

modal.component.html里面:

<button type="button" class="btn btn-default" (click)="buttonClick($event)">click me</button>

如果您嘗試使用 @ViewChild 並且您的按鈕在初始化時在頁面上不可見(由於 *ngIf),則分配將為空。

您可以將 setter 與 @ViewChild 結合使用,並在按鈕首次出現時運行您的初始化。

@ViewChild('btnAdd')
set btnAdd(btnAdd: Button) { ... } 

這很快就會變得笨拙和不方便——特別是如果你從中創建一個可觀察的流。

混合方式可能如下:

btnAskAnotherClicks$ = new Subject<Event>();

<button mat-flat-button (click)="btnAskAnotherClicks$.next($event)">Ask another question...</button>

這允許您使用點擊流來創建鏈,但如果按鈕最初由於 *ngIf 被隱藏,則沒有問題。

不喜歡模板中的next 我也不特別。 但是我對async ,它們都是實現細節。 好吧,這由您決定-)

對於那些使用 AngularMaterial 按鈕和可管道 RxJS 運算符的人,@JoshuaDavid 的回答有一些輕微的修改:

模板中的一些按鈕用模板變量標記:

<button #btnTemplateName mat-icon-button></button>

組件代碼:

import { Observable, fromEvent } from 'rxjs';

// Note importing from lettable/pipeable operators - 'operators' plural
import { tap } from 'rxjs/operators';

import { MatButton } from '@angular/material/button';

//Access the button through the template variable, typed to MatButton
@ViewChild('btnTemplateName') myBtn: MatButton;
myBtnClicks$: Observable<any>;


ngAfterViewInit() {

    // Note the need to access the native element in MatButton through the extended property chain
    this.myBtnClicks$ = 
      Observable.fromEvent(this.myBtn._elementRef.nativeElement, 'click');

    // Can now subscribe (using lettable/pipeable operators)
    this.myBtnClicks$.pipe(
       tap(() => console.log("Button clicked")),
    )
    .subscribe(event => console.log("Event:" + JSON.stringify(event)));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM