前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >RxJS 在 Angular响应式表单中的使用

RxJS 在 Angular响应式表单中的使用

作者头像
mafeifan
发布2019-03-04 17:19:10
5.1K0
发布2019-03-04 17:19:10
举报
文章被收录于专栏:finleyMafinleyMa

响应式表单

FormControlvalueChanges 属性和 statusChanges 属性包含了会发出变更事件的可观察对象。 例子

代码语言:javascript
复制
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl, AbstractControl } from '@angular/forms';
import { concat, merge, zip, combineLatest, race } from 'rxjs/index';
import { filter, map, startWith,  } from 'rxjs/internal/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  form: FormGroup;
  constructor(
    private formBuilder: FormBuilder,
  ) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      username: ['', Validators.required],
      hobby: [''],
    });

    //  监听整个表单
    this.form.valueChanges
          .subscribe( res => console.log(res));
  }
}

HTML

代码语言:javascript
复制
<form [formGroup]="form">
    username: <input type="text" name="username" formControlName="username">
    hobby: 
      <select name="hobby">
        <option value="sleep">sleep</option>
        <option value="play">play</option>
      </select>    
</form>

完善验证,只有通过验证才输出内容 filter 是rxjs提供的运算符

代码语言:javascript
复制
    this.form.valueChanges
    .pipe(
      filter(() => this.form.valid)
    )
    .subscribe(res => console.log(res));

如果需要额外的逻辑,只需要在pipe添加相应的运算符。比如这里在结果里追加上次更新时间,字段名为lastTime

代码语言:javascript
复制
    this.form.valueChanges
    .pipe(
      filter(() => this.form.valid),
      map(data => {
        data.lastTime = new Date();
        return data
     })
    )
    .subscribe(res => console.log(res));

另一种写法,监听各个元素

代码语言:javascript
复制
    // 如果要监听单个表单元素
    const username$ = this.form.get('username').pipe(startWith(this.form.get('username').value))
    const hobby$ = this.form.get('hobby').pipe(startWith(this.form.get('hobby').value))
    //  combineLatest,它会取得各个 observable 最后送出的值,再输出成一个值
    //  这个有个问题是只有合并的元素都产生值才会输出内容,所以在上面使用startWith赋初始化值
    combineLatest(username$, status$)
      .pipe(
        map(([username, status]) => ({username, status}))
      )
      .subscribe(res => console.log(res));
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.02.04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 响应式表单
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档