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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:关于 SAP UI5 Table 控件中行合并的实现方式
下一篇:利用 Angular Directive 和 @HostBinding 实现输入文本框随着键盘输入自动变色效果

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月07日 09时57分01秒