在 module 實現裏,務必導入下列 module:html
import { ReactiveFormsModule } from '@angular/forms';
template 實現代碼:react
<input type="text" [formControl]="jerryFormControl"> <div>{{ response }}</div>
其中 formControl Directive,綁定的是 FormControl 具體實例。Component 完整的實現代碼:git
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { HttpClient} from '@angular/common/http'; import { throttleTime } from "rxjs/operators"; // this endpoint is implemented in https://github.com/wangzixi-diablo/ui5-toolset, local.js const APIENDPOINT = "http://localhost:3000/echo?data="; @Component({ selector: 'jerryform', templateUrl: './react-form.component.html' }) export class JerryReactFormComponent implements OnInit { constructor(private http:HttpClient){} response = ''; onValueChanged = (value)=>{ console.log('new value from live change: ' + value); const url = `${APIENDPOINT}${value}`; const options = { responseType: 'text' as 'json' } var $http = this.http.get(url, options); $http.subscribe( (response:string)=>{ console.log('response from http: ' + response); this.response = response}, (error)=>console.log('error: ' + error)); } ngOnInit(): void { // this.jerryFormControl.valueChanges.pipe(debounceTime(3000)).subscribe(this.onValueChanged); this.jerryFormControl.valueChanges.pipe(throttleTime(2000)).subscribe(this.onValueChanged); } jerryFormControl = new FormControl(''); }
在 Component 的實現代碼裏,咱們並不會直接操做 template 裏的 input 標籤,而是經過其綁定的 formControl 實例 jerryFormControl 暴露出的 valueChanges Observable,來註冊咱們應用程序本身的邏輯,即事件響應函數 onValueChanged.github
使用 rxjs/operators 裏標準的 throttleTime 操做符,實現 2 秒的函數節流。typescript
最後實現的效果:每當 input 標籤頁的輸入發生變化,觸發 onValueChanged 函數,再裏面調用我另外一個 Github倉庫 實現的 echo Service,將 service 結果顯示在 input 字段下方。json
本文完整代碼在這個 commit 裏能找到。函數
更多Jerry的原創文章,盡在:"汪子熙":
ui