Angular – Liên kết dữ liệu với Form

4.9/5 - (43 votes)

Angular cho phép chúng ta kết nối dữ liệu từ form tới các đối tượng trong class.

Tạo form

Để ví dụ thì đầu tiên chúng ta sẽ tạo một form trước đã, ở đây chúng ta sẽ tạo form điền những thông tin thông thường của mô hình khách hàng.

Đầu tiên chúng ta tạo một project mới lấy từ quickstart, đặt tên là gì cũng được, form chẳng hạn.

Sau đó trong thư mục src/app, chúng ta tạo một file có tên customer.ts như sau:

export class Customer{
    constructor(
        public id: number,
        public name: string,
        public age: number,
        public job: string
    ){}
}

Lớp Customer chỉ có một phương thức khởi tạo là constructor() và vài thuộc tính đơn giản.

Tiếp theo chúng ta tạo file customer-form.component.ts trong thư mục src/app như sau:

import { Component } from '@angular/core';
import { Customer } from './customer';

@Component({
    moduleId: module.id,
    selector: 'customer', 
    templateUrl: './customer-form.component.html'
})
export class CustomerFormComponent { 
    jobList = ['Software Developer', 'Tester', 'Project Manager', 'Business Analyst'];
    customer1 = new Customer(1, 'Pho Coder', 24, this.jobList[0]);
}

Ở đây chúng ta định nghĩa lớp component là CustomerFormComponent, lớp này có selector là customer, template lấy từ file khác là customer-form.component.html (chúng ta sẽ viết sau) chứ không code trực tiếp ở đây nữa, để có thể tham chiếu đến file template theo đường dẫn tương đối thì chúng ta phải khai báo tham số moduleId module.id.

Ngoài ra ở đây chúng ta còn import lớp Customer đã định nghĩa ở trên, tạo một mảng jobList lưu danh sách nghề nghiệp, rồi tạo một đối tượng Customercustomer1 với các giá trị đơn giản, trong đó thuộc tính job lấy từ mảng jobList.

Bây giờ chúng ta tạo file template customer-form.component.html cùng thư mục src/app như sau:

<div class="container">
    <h1>Customer</h1> 
    <form> 
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" required>
        </div>
 
        <div class="form-group">
            <label for="age">Age</label>
            <input type="text" class="form-control" id="name" required>
        </div>
 
        <div class="form-group">
            <label for="job">Job</label>
            <select class="form-control" id="job" required>
                <option *ngFor="let job of jobList" [value]="job">{{job}}</option>
            </select>
        </div>
 
        <button type="submit" class="btn btn-success">Submit</button>
     </form>
 </div>

Chúng ta dùng form để hiển thị các trường text, button, combobox…v.v

Ở trường dành cho jobList, chúng ta dùng chỉ thị *ngFor để lặp mảng jobList trong lớp CustomerFormComponent, rồi lấy từng phần tử mảng đó ra làm các item cho thẻ <select>. Cú pháp của *ngFor cũng khá đơn giản, bạn có thể tự suy ra cú pháp là:

let <tên_biến_lặp> of <tên_mảng>

Rồi lấy giá trị thông qua <tên_biến_lặp>.

Ngoài ở nếu bạn để ý thì ở đây chúng ta dùng các lớp CSS của thư viện Bootstrap để làm “màu mè” cho form.

Do đó bây giờ chúng ta chèn thêm đoạn code sử dụng Bootstrap vào file index.html ở trong thư mục src như sau:

<!DOCTYPE html>
<html>
    <head>
    <title>Angular QuickStart</title>
    <base href="/">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">    
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
        System.import('main.js').catch(function(err){ console.error(err); });
    </script>
</head>

<body>
    <my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

Bây giờ chúng ta khai báo form này trong lớp AppComponent, chúng ta sửa file app.component.ts trong thư mục src/app như sau:

import { Component } from '@angular/core';
import { CustomerFormComponent } from './customer-form.component';

@Component({
    selector: 'my-app',
    template: `
        <customer></customer>
    `,
})
export class AppComponent { }

Cuối cùng chúng ta khai báo lớp CustomerFormComponent trong lớp AppModule, chúng ta sửa flle app.module.ts trong thư mục src/app như sau:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { CustomerFormComponent } from './customer-form.component';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ AppComponent, CustomerFormComponent ],
    bootstrap: [ AppComponent ]
})
export class AppModule { }

Ở đây chúng ta còn import thêm một module nữa là FormsModule, module này hỗ trợ một số tính năng để kết nối dữ liệu giữa template và class.

Bây giờ chúng ta có thể chạy project và trang web sẽ có giao diện form như thế này:

Liên kết dữ liệu với form

Chúng ta có thể liên kết các trường trong form với một thuộc tính nào đó trong lớp component tương ứng.

Để làm việc đó thì chúng ta sửa lại file template customer-form.component.html như sau:

<div class="container">
    <h1>Customer</h1> 
    <form> 
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" [(ngModel)]="customer1.name" name="cus1_name" required> 
        </div>
 
        <div class="form-group">
            <label for="age">Age</label>
            <input type="text" class="form-control" id="name" [(ngModel)]="customer1.age" name="cus1_age" required>
        </div>
 
        <div class="form-group">
            <label for="job">Job</label>
            <select class="form-control" id="job" [(ngModel)]="customer1.job" name="cus1_job" required>
                <option *ngFor="let job of jobList" [value]="job">{{job}}</option>
            </select>
        </div>
 
        <button type="submit" class="btn btn-success">Submit</button>
     </form>
 </div>

Chúng ta dùng cú pháp [(ngModel)]="..." trong các thẻ <input> hoặc <select> để kết nối dữ liệu của thẻ đó với một biến thuộc tính nào đó, ở đây chúng ta kết nối đến các thuộc tính name, agejob của đối tượng customer1.

Ngoài ra khi dùng ngModel thì thẻ đó phải khai báo thuộc tính name nữa, giá trị cho thuộc tính này đặt là gì cũng được, không nhất thiết phải là cus1_name, cus1_age

Lưu file này lại, Angular sẽ tự reload lại trang web và bạn sẽ thấy form trên trang web đã tự động điền các giá trị tương ứng với đối tượng customer1.

ngModel có tính chất 2 chiều, tức là nếu chúng ta chỉnh sửa gì trên form thì giá trị của đối tượng customer1 cũng sẽ thay đổi theo.Chúng ta có thể kiểm chứng điều này bằng cách in giá trị của đối tượng customer1 lên như sau:

...
<div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name" [(ngModel)]="customer1.name" name="cus1_name" required> 
    {{ customer1.name }}
</div>
...

5 2 votes
Article Rating
Subscribe
Thông báo cho tôi qua email khi
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments