Trang chủ » Blog » [Thực hành] Ứng dụng tính thời gian đã sống

[Thực hành] Ứng dụng tính thời gian đã sống

bởi CodeGym | 26/12/2023 17:16 | Bài thực hành | Blog

Mục tiêu

Ứng dụng tính thời gian đã sống- Nắm bắt được về các thao tác với service và router trong Angular.

Mô tả- Ứng dụng tính thời gian

Tạo ứng dụng tính thời gian đã sống.

Hướng dẫn

Bước 1: Khởi tạo project với Angular CLI (nếu đã có project thì có thể bỏ qua)

  • Các bạn chạy lệnh npm i date-fns -S để cài đặt thư viện cho việc tính toán datetime.
  • Các bạn chạy lệnh npm i typescript@2.9.2 -D để cài đặt thư viện typescript nếu phiên bản hiện tại < 2.9.2

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

Khởi tạo một service mới tên là date-util.

Tạo file app-routing.module.ts (bỏ qua nếu dùng project mẫu)

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

<h2>Ứng dụng tính thời gian đã sống</h2>

<div>
    <input type="text" (change)="onChange($event.target.value)">
</div>
<p>{{ output }}</p>

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

import { Component, OnInit } from '@angular/core';
import { DateUtilService } from '../date-util.service';

@Component({
    selector: 'app-timelines',
    templateUrl: './timelines.component.html',
    styleUrls: ['./timelines.component.scss']
})
export class TimelinesComponent implements OnInit {
    output = '';
    constructor(private dateUtilService: DateUtilService) { }

ngOnInit() {
}

onChange(value) {
    this.output = this.dateUtilService.getDiffToNow(value);
}

}

Bước 5: Thêm vào app-routing.module.ts:

const routes: Routes = [
    {
        path: 'timelines',
        component: TimelinesComponent

    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes, {
        preloadingStrategy: PreloadAllModules
    })],
    exports: [RouterModule]
})
export class AppRoutingModule {}

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

<nav>
    <a routerLink="timelines" class="link"> Ứng dụng tính thời gian </a>
</nav>
<router-outlet></router-outlet>

Bước 7: Thêm vào app.module.ts

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

Bước 8: Thêm phần code cho date-util service:

import { Injectable } from '@angular/core';
import {
    addMonths,
    addYears,
    differenceInDays,
    differenceInMonths,
    differenceInYears
} from 'date-fns';

@Injectable({
    providedIn: 'root'
})
export class DateUtilService {
    constructor() {}
    getDiffToNow(diff: string | number | Date): string {
        const result: string[] = [];
        const now = new Date();
        diff = new Date(diff);
        const years = differenceInYears(now, diff);
        if (years > 0) {
            result.push(`${years} years`);
            diff = addYears(diff, years);
        }

        const months = differenceInMonths(now, diff);
        result.push(`${months} months`);
        if (months > 0) {
            diff = addMonths(diff, months);
        }

        const days = differenceInDays(now, diff);
        if (days > 0) {
            result.push(`${days} days`);
        }

        return result.join(' ');
    }
}

Bước 9: Kiểm tra kết quả hiển thị trên trình duyệt

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

Trên đây CodeGym đã cùng với bạn luyện tập tạo ứng dụng tính thời gian. 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é!

Download - Giáo trình thuật toán

10 + 1 =

Tags:

0 Lời bình

Gửi Lời bình

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

BÀI VIẾT LIÊN QUAN

BẠN MUỐN HỌC LẬP TRÌNH?

GỌI NGAY

098 953 44 58

Đăng ký tư vấn lộ trình học lập trình

Đăng ký tư vấn, định hướng lộ trình học và giải đáp các thắc mắc về ngành nghề – Miễn phí – Online.

5 + 3 =

TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM
TƯ VẤN VỀ LỘ TRÌNH HỌC NGHỀ LẬP TRÌNH TẠI CODEGYM