MPT Project
MPT Project
// src/app/models/task.model.ts
export interface Task {
id: number;
title: string;
description: string;
completed: boolean;
}
// src/app/services/task.service.ts
import { Injectable } from '@angular/core';
import { Task } from '../models/task.model';
import { BehaviorSubject } from 'rxjs';
addTask(task: Task) {
this.tasks.push({ ...task, id: Date.now(), completed: false });
this.tasksSubject.next(this.tasks);
}
toggleTaskStatus(id: number) {
this.tasks = this.tasks.map(task =>
task.id === id ? { ...task, completed: !task.completed } : task
);
this.tasksSubject.next(this.tasks);
}
deleteTask(id: number) {
this.tasks = this.tasks.filter(task => task.id !== id);
this.tasksSubject.next(this.tasks);
}
}
// src/app/components/task-list/task-list.component.ts
import { Component } from '@angular/core';
import { TaskService } from '../../services/task.service';
@Component({
selector: 'app-task-list',
templateUrl: './task-list.component.html',
styleUrls: ['./task-list.component.scss']
})
export class TaskListComponent {
tasks$ = this.taskService.tasks$;
toggleStatus(id: number) {
this.taskService.toggleTaskStatus(id);
}
deleteTask(id: number) {
this.taskService.deleteTask(id);
}
}
// src/app/components/task-list/task-list.component.html
<ul>
<li *ngFor="let task of (tasks$ | async)">
<span [class.completed]="task.completed">{{ task.title }}</span>
<button (click)="toggleStatus(task.id)">Toggle</button>
<button (click)="deleteTask(task.id)">Delete</button>
</li>
</ul>
// src/app/components/task-form/task-form.component.ts
import { Component } from '@angular/core';
import { TaskService } from '../../services/task.service';
import { Task } from '../../models/task.model';
@Component({
selector: 'app-task-form',
templateUrl: './task-form.component.html',
styleUrls: ['./task-form.component.scss']
})
export class TaskFormComponent {
taskTitle = '';
taskDescription = '';
addTask() {
if (this.taskTitle.trim()) {
this.taskService.addTask({
id: 0,
title: this.taskTitle,
description: this.taskDescription,
completed: false,
});
this.taskTitle = '';
this.taskDescription = '';
}
}
}
// src/app/components/task-form/task-form.component.html
<input [(ngModel)]="taskTitle" placeholder="Task Title" />
<input [(ngModel)]="taskDescription" placeholder="Task Description" />
<button (click)="addTask()">Add Task</button>
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { TaskListComponent } from './components/task-list/task-list.component';
import { TaskFormComponent } from './components/task-form/task-form.component';
@NgModule({
declarations: [AppComponent, TaskListComponent, TaskFormComponent],
imports: [BrowserModule, FormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}