zoukankan      html  css  js  c++  java
  • 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.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.

    使用 rxjs/operators 里标准的 throttleTime 操作符,实现 2 秒的函数节流。

    最后实现的效果:每当 input 标签页的输入发生变化,触发 onValueChanged 函数,再里面调用我另一个 Github仓库 实现的 echo Service,将 service 结果显示在 input 字段下方。

    本文完整代码在这个 commit 里能找到。

    更多Jerry的原创文章,尽在:"汪子熙":

  • 相关阅读:
    selenium+java利用AutoIT实现文件上传
    java+selenium自动化遇到confirm弹窗,出现NoAlertPresentException: no alert open
    Appium遇到问题:
    selenium2+java切换窗口
    nodejs
    连续12天的加班工作总结-根据客户选择来生成后续表单页面
    最近三家公司面试的总结吐槽及一点点总结
    nodeJs-autoMerge
    nodeJs-autoBulid
    Angular 学习笔记——ng-Resource1
  • 原文地址:https://www.cnblogs.com/sap-jerry/p/14852742.html
Copyright © 2011-2022 走看看