Validation FormBuilder
Bước 1: Tạo project Angular 2 bấm vào đây
app.component.ts
Angular 2+
import { FormGroup, FormBuilder, Validators } from '@angular/forms'; constructor(private formBuilder: FormBuilder) {} ngOnInit() { this.registerForm = this.formBuilder.group({ firstName: ['', Validators.required], lastName: ['', Validators.required], email: ['', [Validators.required, Validators.email]], password: ['', [Validators.required, Validators.minLength(6)]] }); } // convenience getter for easy access to form fields get f() { return this.registerForm.controls; }
app.component.html
Angular 2+
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }"/> <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback"> <div *ngIf="f.firstName.errors.required">First Name is required</div> </div>
app.module.ts
Angular 2+
import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ imports: [ReactiveFormsModule], })
styles.css
Angular 2+
/* Add application styles & imports to this file! */ @import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css');
ng serve --live-reload
0 nhận xét:
Post a Comment