[Angular2 Form] Use RxJS Streams with Angular 2 Forms

來源:互聯網
上載者:User

標籤:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.