top of page

Anguler Js - Create a todo list in Anguler js


  1. Set up a new Angular project by installing Angular CLI and creating a new project. Open a terminal and run the following commands:


npm install -g @angular/cli
ng new todo-list
cd todo-list
  1. Create a new component for the todo list. Run the following command to generate a new component:


ng generate component todo

This will generate a new component named "todo" along with its files.

  1. Open the todo.component.html file and replace the existing content with the following HTML code:

html
<h2>Todo List</h2>
<input type="text" [(ngModel)]="newItem" placeholder="Add a new item"><button (click)="addItem()">Add</button>
<ul>
<li *ngFor="let item of todoItems; let i = index">
    {{ item }}
<button (click)="removeItem(i)">Remove</button></li></ul>
  1. Open the todo.component.ts file and replace the existing code with the following TypeScript code:

typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css']
})
export class TodoComponent {
  newItem: string;
  todoItems: string[] = [];

  addItem() {
    this.todoItems.push(this.newItem);
    this.newItem = '';
  }

  removeItem(index: number) {
    this.todoItems.splice(index, 1);
  }
}
  1. Open the app.component.html file and replace the existing content with the following code:

html
<app-todo></app-todo>
  1. Run the Angular development server by executing the following command in the terminal:

bash
ng serve
  1. Open your web browser and visit http://localhost:4200 to see the todo list in action.

Now, you should have a basic todo list implemented in Angular 12. You can add new items, remove items, and see them displayed in the list. Feel free to customize the styling and enhance the functionality based on your requirements.

Related Posts

See All

Bình luận


bottom of page