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

  • 相关阅读:
    Android应用开发笔记——打造自己的标签栏
    ZeroMQ 的模式[转]
    安装python/wingware
    新手该如何学python怎么学好python?
    membase 简介
    前端学习网站推荐
    签了工作之后才发现,自己太草率了.....我看过的关于职业规划最好最全面的一篇文章[转]
    Nagio监控系统介绍
    thread_union位置
    音频采样位数问题
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5914983.html
Copyright © 2011-2022 走看看