ReactiveForm
ReactiveForm is Angular module for form building
Compare to template-driven style,
- More flexible
- Immutable data model
- Easier to perform an action on a value change
- Support Reactive transoformaton
- Easier to do Unit Test
Let’s try
This is a basic sample to support ReactiveForm.
Create component first
> ng g component getstartreactiveform
getstartreactiveform.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './getstartreactiveform.component.html', styleUrls: ['./getstartreactiveform.component.css'] }) export class GetstartreactiveformComponent implements OnInit { testForm: FormGroup; constructor() { } ngOnInit(): void { this.testForm = new FormGroup({ firstName: new FormControl(), lastName: new FormControl(), email: new FormControl() }); } save() { console.log(this.testForm); console.log('Saved: ' + JSON.stringify(this.testForm.value)); } }
getstartreactiveform.component.html
<form (ngSubmit)="save()" [formGroup]="testForm"> <input id="firstNameId" type="text" placeholder="" formControlName="firstName" [ngClass]="{'is-valid': (testForm.get('firstName').touched || testForm.get('firstName').dirty)}"/> <br> <input id="lastNameId" type="text" placeholder="" formControlName="lastName" [ngClass]="{'is-valid': (testForm.get('lastName').touched || testForm.get('lastName').dirty)}"/> <br> <input id="emailId" type="email" placeholder="" formControlName="email" [ngClass]="{'is-valid': (testForm.get('email').touched || testForm.get('email').dirty)}"/> <br> <button class="btn btn-primary mr-3" type="submit" style="width:80px" [disabled]="!testForm.valid">Save</button> </form>
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { ChildComponent } from './databind/child.component'; import { GetstartreactiveformComponent } from './formsamples/getstartreactiveform/getstartreactiveform.component'; @NgModule({ declarations: [ AppComponent, ChildComponent, GetstartreactiveformComponent ], imports: [ BrowserModule, HttpClientModule, ReactiveFormsModule ], providers: [], bootstrap: [GetstartreactiveformComponent] }) export class AppModule { }
Form Status
FormControl has status, and we can check each component status.
touched | User focus control |
dirty | Change value dirty <-> pristine |
valid | true : no validator, or all validator apss |
Update Form value by code
Use setValue or patchValue
// Set Value this.testForm.setValue({ firstName: 'Jack', lastName: 'Lim', email: 'jack@daiji110.com' }); // Patch Value this.testForm.patchValue({ firstName: 'Jack', lastName: 'Lim' });
setValue : Change All values in form
patchValue : Change a part of values in form
コメント