Thursday, September 17, 2020

Tìm hiểu Form trong Angular 7

Trong bài học này chúng ta sẽ tìm hiểu cách sử dụng form trong angular 7 như thế nào,và sử dụng ra sao,phân biệt sự khác biệt 2 cách làm việc form

  • Template driven form
  • Model driven form

Template Driven Form

Với template driven form hầu hết công việc được thực hiện trong form còn với model driven form hầu hết công việc được thực hiện trong component.

Để làm việc với biểu mẫu Template driven form chúng ta phải import formModule từ @angular/forms được thiết lập trong app.module.ts như dưới đây:

import { BrowserModule } from '@angular/platform-browser';

import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';

import { ChangeTextDirective } from './change-text.directive';

import { AppRoutingModule, RoutingComponet } from './app-routing.module';

import { HomeComponent } from './home/home.component';

import { AboutComponent } from './about/about.component';

import { MyServiceService } from './service/my-service.service';

import { NewHomeComponent } from './home/new-home/new-home.component';

import { HttpClientModule } from '@angular/common/http';

import { FormComponent } from './form/form.component';

import { FormsModule } from '@angular/forms';


@NgModule({

  declarations: [

    AppComponent,

    ChangeTextDirective,

    HomeComponent,

    AboutComponent,

    RoutingComponet,

    NewHomeComponent,

    FormComponent

  ],

  imports: [

    BrowserModule,

    AppRoutingModule,

    HttpClientModule,

    FormsModule

  ],

  providers: [MyServiceService],

  bootstrap: [AppComponent]

})

export class AppModule { }

Bây giờ tạo một component trong file form.component.html chèn mã form vào

<div>

    <form #formLogin="ngForm" (ngSubmit) ="onclickSubmit(formLogin.value)">

        <input type = "text" name = "emailid" placeholder = "emailid" ngModel> 

        <br/> 

        <input type = "password" name = "passwd" placeholder = "passwd" ngModel> 

        <br/> 

        <input type = "submit" value = "submit"> 

    </form>

</div>

Bây giờ chúng ta mới đi vào sự kiện trong form.component.ts

import { Component, OnInit } from '@angular/core';


@Component({

  selector: 'app-form',

  templateUrl: './form.component.html',

  styleUrls: ['./form.component.css']

})

export class FormComponent implements OnInit {


  constructor() { }


  ngOnInit(): void {

  }

  onclickSubmit(value){

    if(value.emailid !="tienanh@gmail.com"){

      alert("Xin loi");

    }else if(value.passwd!="12345"){

      alert("Xin loi");

    }else{

      alert("WELLCOME");

    }

  }


}

Thiết lập lại css cho form 

input[type = text], input[type = password] { 

    width: 40%; 

    padding: 12px 20px; 

    margin: 8px 0; 

    display: inline-block; 

    border: 1px solid #B3A9A9; 

    box-sizing: border-box; 

 } 

 input[type = submit] { 

    padding: 12px 20px; 

    margin: 8px 0; 

    display: inline-block; 

    border: 1px solid #B3A9A9; 

    box-sizing: border-box; 

 }

 Kết quả của chương trình trên:


 Model Driven Form

 Trong model driven form để sử dụng được chúng ta cần import ReactiveFormsModule từ @angular/forms

   imports: [

    BrowserModule,

    AppRoutingModule,

    HttpClientModule,

    FormsModule,

    ReactiveFormsModule

  ]

  form.component.ts

  export class Form2Component implements OnInit {

  email;

  formData;

  constructor() { }


  ngOnInit(): void {

    this.formData = new FormGroup({

      emailid: new FormControl("anh@gmail.com"),

      passwd: new FormControl("12345")

    });

  }

  onClickSubmit(data){

     alert(data.emailid);

     this.email  = data.emailid;

   }

}

form.component.html

<div> 

    <form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" > 

       <input type = "text" class = "fortextbox" name = "emailid" placeholder = "Email" 

          formControlName = "emailid"> 

       <br/> 

       

       <input type = "password" class = "fortextbox" name = "passwd" 

          placeholder = "passwd" formControlName = "passwd"> 

       <br/>

       

       <input type = "submit" class = "forsubmit" value = "Log In"> 

    </form>

 </div> 

 <p> Email entered is : {{email}} </p>

 form.component.ts

 import { Component, OnInit } from '@angular/core';

import { FormControl, FormGroup } from '@angular/forms';


@Component({

  selector: 'app-form2',

  templateUrl: './form2.component.html',

  styleUrls: ['./form2.component.css']

})

export class Form2Component implements OnInit {


  email;

  formData;

  constructor() { }


  ngOnInit(): void {

    this.formData = new FormGroup({

      emailid: new FormControl("anh@gmail.com"),

      passwd: new FormControl("12345")

    });

  }

  onClickSubmit(data){

     alert(data.emailid);

     this.email  = data.emailid;

   }

}

Form Validaton trong Angular

Bây giờ chúng ta hãy thảo luận về xác thực biểu mẫu bằng cách sử dụng model driven form. Bạn có thể sử dụng xác thực biểu mẫu có sẵn hoặc cũng có thể sử dụng phương pháp xác thực tùy chỉnh. Chúng tôi sẽ sử dụng cả hai cách tiếp cận trong form. Chúng tôi sẽ tiếp tục với cùng một ví dụ mà chúng tôi đã tạo trong một trong các phần trước của chúng tôi. Với Angular 7, chúng ta cần nhập Validators từ @angular/ form như hình dưới đây

import { FormGroup, FormControl, Validators} from '@angular/forms'

Angular có các trình xác thực tích hợp như trường bắt buộc, độ dài tối thiểu, độ dài tối đa và mẫu. Chúng phải được truy cập bằng module Validators.

Bạn chỉ có thể thêm trình xác thực hoặc một mảng trình xác thực cần thiết để cho Angular biết nếu một trường cụ thể là bắt buộc. Bây giờ chúng ta hãy thử tương tự trên một trong các hộp văn bản đầu vào, tức là id email. Đối với id email, chúng tôi đã thêm các thông số xác thực sau

Trong file form.component.ts bạn thực hiện validator trong angular của form

import { Component, OnInit } from '@angular/core';

import { FormGroup, FormControl, Validators} from '@angular/forms';


@Component({

  selector: 'app-form2',

  templateUrl: './form2.component.html',

  styleUrls: ['./form2.component.css']

})

export class Form2Component implements OnInit {


  public email;

  public formdata;

  constructor() { }


  ngOnInit(): void {

    this.formdata = new FormGroup({

      emailid: new FormControl("", Validators.compose([

         Validators.required,

         Validators.pattern("[^ @]*@[^ @]*")

      ])),

      passwd: new FormControl("")

   });

  }

  onClickSubmit(data){

     alert(data.emailid);

     this.email  = data.emailid;

   }

}

Để thực hiện được validator form của angular bạn cần phải chỉnh sửa thêm một chút để người dùng có thể biết được các giá trị mà họ nhập sai hoặc thiếu ở html

<div> 

    <form [formGroup] = "formdata" (ngSubmit) = "onClickSubmit(formdata.value)" > 

       <input type = "text" class = "fortextbox" name = "emailid" placeholder = "Email" 

          formControlName = "emailid"> 

       <br/> 

       

       <input type = "password" class = "fortextbox" name = "passwd" 

          placeholder = "passwd" formControlName = "passwd"> 

       <br/>

       

       <input type = "submit" [disabled] ="!formdata.valid" class = "forsubmit" value = "Log In"> 

    </form>

 </div> 

 <p> Email entered is : {{email}} </p>

 Kiểm tra các giá trị nhập sai 

 [disabled] ="!formdata.valid"

Bạn có thể dùng hàm để kiểm tra các giá trị nhập vào của password

  passwordvalidation(formcontrol){

     if(formcontrol.value.length <5){

       return {"passwd":true};

     }

   }

 Cần khai báo trong Formdata

 this.formdata = new FormGroup({

      emailid: new FormControl("", Validators.compose([

         Validators.required,

         Validators.pattern("[^ @]*@[^ @]*")

      ])),

      passwd: new FormControl("",this.passwordvalidation)

   });

No comments:

Post a Comment