FormControl リアクティブフォーム (Angular)

リアクティブフォームは、時間とともに値が変化するフォーム入力を処理するためのモデル駆動型アプローチを提供します。 以下にサンプルコードを記載します。

  • app.components.ts
import {Component, PipeTransform} from '@angular/core';
import { FormControl} from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  text1 = new FormControl(); //Formを取り扱うFormControlをnewする。
  s: string ='';

  ngOnInit(){
    this.text1.valueChanges     //valueChangeは、Formが変更するたびに検知するObservableのmethod
      .subscribe(a => {console.log(a);  //Observableであるために、subscribeで、入力値を取得する。
      this.s = a;
      })
  }
}
  • app.component.html
<input [formControl]="text1" type="text">
<div>{{s}}</div>

以下のようなリアクティブなフォームが表示されます。