Angular Reactive Form 的一个具体使用例子
生活随笔
收集整理的這篇文章主要介紹了
Angular Reactive Form 的一个具体使用例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在 module 實現里,務必導入下列 module:
import { ReactiveFormsModule } from '@angular/forms';template 實現代碼:
<input type="text" [formControl]="jerryFormControl"> <div>{{ response }}</div>其中 formControl Directive,綁定的是 FormControl 具體實例。Component 完整的實現代碼:
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.jsconst 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.
使用 rxjs/operators 里標準的 throttleTime 操作符,實現 2 秒的函數節流。
最后實現的效果:每當 input 標簽頁的輸入發生變化,觸發 onValueChanged 函數,再里面調用我另一個 Github倉庫 實現的 echo Service,將 service 結果顯示在 input 字段下方。
本文完整代碼在這個 commit 里能找到。
更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的Angular Reactive Form 的一个具体使用例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构与算法(周测7-拓扑排序和AOV
- 下一篇: 基于rv1108的以太网PHY层芯片LA