Have 2 ways validate form in angular.

First Way: Use FormBuilder

HTML file

 <form [formGroup]="angForm" novalidate>

<div class="form-group"> <label class="center-block">Name: <input class="form-control" formControlName="name"> </label> </div> <div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger"> <div *ngIf="angForm.controls['name'].errors.required"> Name is required. </div> </div> </form> <p>Form value: {{ angForm.value | json }}</p> <p>Form status: {{ angForm.status | json }}</p>

TS file

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular Form Validation Tutorial'; angForm: FormGroup; constructor(private fb: FormBuilder) { this.createForm(); } createForm() { this.angForm = this.fb.group({ name: ['', Validators.required ] }); } }

Second Way: Use ngModel
Create model file class
    
export class ContactForm {
    constructor(
        public namestring,
        public emailstring,
        public subjectstring,
        public phone?: string,
        public content?: string
    ) { }
}

HTML File
<form (ngSubmit)="onSubmit()" #requestForm="ngForm" id="requestForm" name="requestForm">
    <div class="row">
        <div class="col-lg-6">
            <input class="form-control" type="text" name="name" value="" size="40" required minlength="2" appForbiddenName="admin"
            [(ngModel)]="model.name" #name="ngModel" #_name placeholder="(1) Họ tên *">
            
        </div>
        <div class="col-lg-6">
            <input class="form-control" type="email" name="email" #_email value="" size="40"
                aria-required="true" aria-invalid="false" placeholder="Email">
        </div>
        <div class="col-lg-6">
            <input class="form-control" type="text" name="subject" value="" size="40" required minlength="3" #_subject
                #subject="ngModel" [(ngModel)]="model.subject" aria-invalid="false" placeholder="(2) Tiêu đề *">
        </div>

        <div class="col-lg-6">
            <input class="form-control" type="text" name="phone" value="" size="40" required pattern="^\+?(?:[0-9]??).{5,14}[0-9]$" #_phone
                #phone="ngModel" [(ngModel)]="model.phone" aria-required="true" aria-invalid="false" placeholder="(3) Số điện thoại *">
        </div>
        <div class="col-xs-12">
            <textarea class="form-control" name="message" cols="40" rows="4" required #_message
            #message="ngModel" [(ngModel)]="model.content" aria-invalid="false" placeholder="(4) Nội dung bạn quan tâm *"></textarea>
        </div>
        <div class="col-xs-12">
            <input class="btn btn-primary" [disabled]="!requestForm.form.valid" type="submit" #submit_bt value="    Gửi    ">
        </div>
    </div>
</form>
<div>
    <p *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
        <span *ngIf="name.errors.required">
            (1) Họ tên không được trống.
        </span>
        <span *ngIf="name.errors.minlength">
            (1) Tên ít nhất phải 2 ký tự.
        </span>
        <span *ngIf="name.errors.forbiddenName">
            (1) Tên bạn không thể là "admin".
        </span>
    </p>
    <p *ngIf="subject.invalid && (subject.dirty || subject.touched)" class="alert alert-danger">
        <span *ngIf="subject.errors.required">
            (2) Tiêu đề không được trống.
        </span>
        <span *ngIf="subject.errors.minlength">
            (2) Tiêu đề ít nhất phải 3 ký tự.
        </span>
    </p>
    <p *ngIf="phone.invalid && (phone.dirty || phone.touched)" class="alert alert-danger">
        <span *ngIf="phone.errors.required">
            (3) Số điện thoại không được trống.
        </span>
        <span *ngIf="phone.errors.pattern">
            (3) Điện thoại không đúng định dạng.
        </span>
    </p>
    <p *ngIf="message.invalid && (message.dirty || message.touched)" class="alert alert-danger">
        <span *ngIf="message.errors.required">
            (4) Nội dung không được trống.
        </span>
    </p>
</div>

TS File

import { Contact } from '../../Class/contact';
model = new Contact('','','','','');
  @ViewChild('_name', {static: true}) name: ElementRef;
  @ViewChild('_subject', {static: true}) subject: ElementRef;
  @ViewChild('_phone', {static: true}) phone: ElementRef;
  @ViewChild('_email', {static: true}) email:ElementRef;
  @ViewChild('_message', {static: true}) message: ElementRef;
  // @ViewChild('submit_bt',{static: true}) submit_bt: ElementRef;
  async onSubmit(){
    let _name = this.name.nativeElement.value;
    let _subject = this.subject.nativeElement.value;
    let _phone = this.phone.nativeElement.value;
    let _email = this.email.nativeElement.value;
    let _message = this.message.nativeElement.value;
    alert(_name + " - " + _subject + " - " + _phone + " - " + _email + " - " + _message)
  }

Không cần khai báo trong ts file, nhưng muốn lấy giá trị form cần dùng @ViewChild('Name',{static:true}) name:ElementRef;


0 Comments: