Có hai cách để làm việc với form trong Angular, đó là template-driven và reactive. Hai cách này thực hiện khác nhau khi xử lý dữ liệu và sự kiện trong form. Mỗi cách có những thuận lợi riêng.
//login.component.ts import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-login', standalone: true, imports: [ FormsModule, CommonModule ], templateUrl: './login.component.html', styleUrl: './login.component.css' }) export class LoginComponent { }
c. Tạo form với template driven trong angular
C>c. Tạo form với template driven trong angularo biến ngform vào tag form và gắn ngModel vào từng control của form. Mỗi control trong form phải có biến name.
Lấy giá trị từ form : Với cách dùng[(ngModel)] như trên thì các giá trị user nhập tự động đưa vào các biến tương ứng username. Các control cần có tham số name để có thể truy xuất giá trị trong view (xem hình dưới)
f. Kiểm tra dữ liệu trong form (validation)
Angular hỗ trợ kiểm tra dữ liệu trong form với các quy tắc dữ liệu nhập bạn chỉ ra. Ví dụ required, min, max, minlength, maxlength, type=email, type=date, ty>f. Kiểm tra dữ liệu trong form (validation)aph">– Đầu tiên, bạn định nghĩa các quy tắc hợp lệ của dữ liệu trong control của form. Ví dụ sau là 2 quy tắc:
Bạn kết hợp *ngIf và các biến trạng thái lỗi để hiện các thông báo lỗi cho thân thiện hơn. Dùng invalid để hiện lỗi chung cho mọi quy tắc, hoặc dùng errors để hiện riêng từng lỗi cũng được. Xem ví dụ sau:
g. Định dạng các control trong form theo trạng thái
Angular tự động gán các class css của các form control theo trạng thái nhập liệu của user. Sau đây là các class được hỗ trợ: .ng-valid , .ng-invalid , .ng-pending , .ng-pristine, .ng-dirty, .ng-untouched, .ng-touched, .ng-submitted (enclosing form element only)
g. Định dạng các control trong form theo trạng thái/wp-content/uploads/2024/04/image-53-1024x308.png" alt="" class="wp-image-8884" srcset="https://longnv.name.vn/wp-content/uploads/2024/04/image-53-1024x308.png 1024w, https://longnv.name.vn/wp-content/uploads/2024/04/image-53-300x90.png 300w, https://longnv.name.vn/wp-content/uploads/2024/04/image-53-768x231.png 768w, https://longnv.name.vn/wp-content/uploads/2024/04/image-53-696x210.png 696w, https://longnv.name.vn/wp-content/uploads/2024/04/image-53-1068x322.png 1068w, https://longnv.name.vn/wp-content/uploads/2024/04/image-53-1395x420.png 1395w, https://longnv.name.vn/wp-content/uploads/2024/04/image-53.png 1425w" sizes="auto, (max-width: 1024px) 100vw, 1024px" />
Việc angular tự động gán các class css như trên là rất hay. Bạn có thể tạo css trùng tên các class này để định dạng control theo các trạng thái của nó. Ví dụ tạo css định dạng các control mà user nhập không đúng quy tắc.
h. Xử lý submitort class LoginComponent {
username:string='teonv';
password:string='123';
xuly(d:any){
console.log("Data: ",d);
console.log("Username=", this.username);
console.log("Password=", this.password);
}
}
Khi gọi hàm xử lý, có thể truyền tham số cho hàm như ví dụ trên hoặc có thể dùng các biến trong class đã được bind từ form
2. Reactive Form trong Angular
Reactive form còn gọi là model driven form là cách tạo form thứ 2. Với cách này, đối tượng form và các thành phần được tạo bằng cách code trong file component.ts rồi bind ra view.
Các thành phần trong form reactive
FormControl: tương ứng với 1 HTML form control như input, select, textarea…
FormGroup : là một nhóm các đối tượng FormControl, FormGroup…
a. Tạo component
2. Reactive Form trong Angularre>
Nhúng component vào app
Các thành phần trong form reactiveent.html import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; a. Tạo component, 0, 0)" class="has-inline-color has-vivid-red-color">import { DangkyComponent } from './dangky/dangky.component'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet , DangkyComponent], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = 'Sử dụng form' }
Sau khi có template, bạn itạo đối tượng FormGroup cho Form. Và tạo FormControl cho từng control trong form. Code trong hàm contructor hoặc ngOnInit của component.
//dangky.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-dang>d. Code tạo đối tượng form reactiveground-color:rgba(0, 0, 0, 0)" class="has-inline-color has-black-color"> import { FormGroup, FormControl, ReactiveFormsModule , CommonModule } from '@angular/forms';
templateUrl: './dangky.component.html',
styleUrl: './dangky.component.css'
})
export class DangkyComponent {
frm1!: FormGroup;
ngOnInit(): void {
this.frm1 = new FormGroup({
username: new FormControl('yêulắm'),
password: new FormControl('lâmyếu'),
email: new FormControl('yeulắmlâmyếu@gmail.com'),
});
}
}
e. Binding control
Sau khi có template và đối tượng, bạn bind ra template trong tag form và các control như sau:
Sử dụng cú pháp tênform.value. Ví dụ : frm1.value , sẽ lấy được các giá trị trong form.
<p>Form value {{frm1.value | json }}</p> <p>Username: {{frm1.value.username}}</p> </form>
f. Lấy giá trị trong formontent/uploads/2024/04/image-57-300x128.png 300w, https://longnv.name.vn/wp-content/uploads/2024/04/image-57-768x327.png 768w, https://longnv.name.vn/wp-content/uploads/2024/04/image-57-696x296.png 696w, https://longnv.name.vn/wp-content/uploads/2024/04/image-57-1068x454.png 1068w, https://longnv.name.vn/wp-content/uploads/2024/04/image-57-987x420.png 987w, https://longnv.name.vn/wp-content/uploads/2024/04/image-57.png 1286w" sizes="auto, (max-width: 1024px) 100vw, 1024px" />
g. Reactive form validator
Việc kiểm tra dữ liệu nhập trong các control của form thực hiện bằng cách thêm Validator vào form control. Thực hiện bằng cách thêm quiy tắc Validators trong tham số thứ 2 như dưới đây
//dangky.component.ts import { Validators } from '@angular/forms'; ... export class DangkyComponent { frm1!: FormGroup; ngOnInit(): void { this.frm1 = new FormGroup({ username: new FormControl('yêulắm', [Validators.minLength(6)]), >g. Reactive form validatoru' , [Validators.minLength(8), Validators.maxLength(20)] ), email: new FormControl('yeulắmlâmyếu@gmail.com'), }); } }