[Angular2 Form] Use RxJS Streams with Angular 2 Forms

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Angular2 Form] Use RxJS Streams with Angular 2 Forms相关的知识,希望对你有一定的参考价值。

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

以上是关于[Angular2 Form] Use RxJS Streams with Angular 2 Forms的主要内容,如果未能解决你的问题,请参考以下文章

Rxjs 过滤器运算符不适用于 Angular2 Observable

在 Angular2 中使用 RxJS 链接 observables

angular2 学习笔记 ( rxjs 流 )

Angular2 RxJS 得到“Observable_1.Observable.fromEvent 不是函数”错误

Angular2 beta.12 和 RxJs 5 beta.3 的可观察到的错误

[RxJS] Use groupBy in real RxJS applications