FormBuilder
Last post, I show the example of ReactiveForm.
To make this simple, we can use FormBiulder
FormBuilder create a form model from a configuration
Shortens boilderplate code
Provide as a service (constructor)
Let’s take a look
This sample is almost same as (Angular Reactiveform Get Started)
Sample Code
formbuildersample.component.ts
import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { FormGroup } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './formbuildersample.component.html', styleUrls: ['./formbuildersample.component.css'] }) export class FormbuildersampleComponent implements OnInit { testForm: FormGroup; constructor(private fb: FormBuilder) { } ngOnInit(): void { this.testForm = this.fb.group({ firstName: null, lastName: null, email: null }); } save() { console.log(this.testForm); console.log('Saved: ' + JSON.stringify(this.testForm.value)); } }
formbuilder.component.html
<h2>Home Builder</h2> <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>
The result is same as previous. Input all values in input field and press “submit”, you can see console log form information.
Become simple? Yeah.
コメント