[Angular2 Form] Use RxJS Streams with Angular 2 Forms

本文介绍如何使用Angular2中的表单功能结合RxJS来处理表单数据和有效性检查。通过示例展示了如何监听表单状态变化并在表单有效时记录表单值。

Angular 2 forms provide RxJS streams for you to work with the data and validity as it flows out of the forms. These streams allow you handle complex scenarios and asynchronous scenarios with relative ease. This example shows you how to log out the values of the form when the form is valid.

 

  <!--

    Learn @ViewChld()
    valueChanges: show the value,
    statusChanges: show VALIDE or INVALIDE,
    Observable.combineLatest

  -->
  <form #myForm3="ngForm" name="myForm3">
    <input type="text" #techRef="ngModel" ngModel required placeholder="Type Angular2..." name="tech" pattern="Angular2">
    <span *ngIf="techRef.valid" class="success-message">{{answer}}</span>
  </form>
  <div class="error-messages" *ngIf="!myForm3.valid">
    <span class="error-message" *ngIf="techRef.errors?.pattern">{{techRef.errors?.pattern.requiredPattern}} only</span>
    <span class="error-message" *ngIf="techRef.errors?.required">Requried</span>
  </div>
  <pre>
    Input: {{techRef.errors | json}}
  </pre>

 

import {Component, OnInit, ViewChild} from '@angular/core';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-message',
  templateUrl: './message.component.html',
  styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {

  @ViewChild('myForm3') form;

  message = "Hello";
  answer: string;

  constructor() {
  }

  ngOnInit() {
  }

  onSubmit(formValue) {
    console.log("formValue", JSON.stringify(formValue, null, 2))
  }

  ngAfterViewInit() {
    this.form.valueChanges
      .subscribe((res) => console.table(res));

    this.form.statusChanges
      .subscribe((res) => console.log(res));

    Observable
      .combineLatest(
        this.form.valueChanges,
        this.form.statusChanges,
        (value, status) => ({value, status})
      )
      .filter( ({status}) => {
        return status === "VALID";
      })
      .subscribe( val => {
        this.answer = "You are right!";
      })

  }
}

 

Github

转载于:https://www.cnblogs.com/Answer1215/p/5914983.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值