Angular Reactive Form 的一个具体使用例子
发布日期:2021-06-30 14:49:01
浏览次数:2
分类:技术文章
本文共 1820 字,大约阅读时间需要 6 分钟。
在 module 实现里,务必导入下列 module:
import { ReactiveFormsModule } from '@angular/forms';
template 实现代码:
{ { response }}
其中 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 函数,再里面调用我另一个 实现的 echo Service,将 service 结果显示在 input 字段下方。
本文完整代码在这个 里能找到。
更多Jerry的原创文章,尽在:“汪子熙”:
转载地址:https://jerry.blog.csdn.net/article/details/117469099 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2024年04月07日 09时57分01秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
nginx访问控制、基于用户认证、https配置
2019-04-30
linux内存的寻址方式
2019-04-30
how2heap-double free
2019-04-30
how2heap-fastbin_dup_consolidate
2019-04-30
tf keras SimpleRNN源码解析
2019-04-30
MyBatisPlus简单入门(SpringBoot)
2019-04-30
攻防世界web进阶区web2详解
2019-04-30
xss-labs详解(上)1-10
2019-04-30
xss-labs详解(下)11-20
2019-04-30
攻防世界web进阶区ics-04详解
2019-04-30
sql注入总结学习
2019-04-30
Python 之 histogram直方图
2019-04-30
Python实现决策树 Desision Tree & 可视化
2019-04-30
决策树 Decision tree
2019-04-30
nominal和ordinal & 数据处理中四种基本数据类型
2019-04-30
Trie树(字典树)
2019-04-30
MATLAB与CUDA
2019-04-30
Linux png转jpg (convert命令)
2019-04-30
Ubuntu更新后终端中字体的颜色全是白色
2019-04-30