Mục tiêu

Tạo ứng dụng todo.

Nắm bắt được về các thao tác với form trong Angular.

Mô tả- tạo ứng dụng todo

Tạo ứng dụng Todo.

Hướng dẫn

Bước 1: Khởi tạo project với Angular CLI

Bước 1.1: Import thêm các stylesheet của thư viện bootstrap:

Các bạn mở terminal/CMD trong project, sau đó chạy lệnh npm i bootstrap -s.

Mở file styles.scss, sau đó thêm đoạn code sau:

@import '~bootstrap/scss/bootstrap';

Bước 2: Khởi tạo một component mới trong project và đặt tên là todo

Bước 3: Thay phần template của component vừa tạo bằng đoạn code sau:

<h2 class="text-center">
    Todo App
</h2>
<div class="col-md-8 offset-md-2">
    <div>
        <input class="form-control" type="text" [formControl]="userInput" (change)="onChange()">
    </div>

    <ul>
        <li (click)="toggleTodo(i)"
            [class.complete]="todo.complete"
            *ngFor="let todo of todos; index as i">
            {{todo.content}}
        </li>
    </ul>
</div>

Bước 4: Đặt thêm stylesheet sau vào file style của component(todo.component.scss):

.complete {
    text-decoration: line-through;
}

Bước 5: Code phần logic cho component

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

interface ITodo {
    id: number;
    content: string;
    complete: boolean;
}

let _id = 1;

@Component({
    selector: 'app-todo',
    templateUrl: './todo.component.html',
    styleUrls: ['./todo.component.scss']
})
export class TodoComponent implements OnInit {
    userInput = new FormControl();
    todos: Array<ITodo> = [];
    constructor() { }

    ngOnInit() {
    }

    onChange() {
        const {value} = this.userInput;
        if (value) {
            const todo: ITodo = {
                id: _id++,
                content: value,
                complete: false
            };
            this.todos.push(todo);
            this.userInput.setValue('');
        }
    }

    toggleTodo(i) {
        this.todos[i].complete = !this.todos[i].complete;
    }

}

Bước 6: Thêm vào app.component.html:

<app-todo></app-todo>

Bước 7: Kiểm tra kết quả có giống với hình sau:

Lưu ý: khi click vào phần từ ở list bên dưới, phần tử đó sẽ bị gạch ngang để biểu thị đã hoàn thành, có thể click nhiều lần để toggle trạng thái

Mã nguồn tham khảo: https://github.com/codegym-vn/angular-training/tree/master/angular-form/src/app

Trên đây CodeGym đã cùng với bạn luyện tập thao tác với form trong Angular. Hãy chụp ảnh màn hình và nộp bài thực hành của bạn trên CodeGymX để cùng nhau luyện tập nhé!

Exit mobile version