How To Add And Delete Data In Angular

Introduction

Add and delete operations are used to store and remove data from the database. If the user wants to add the data then the user has to perform the post-operation and if the user wants to remove the data from the database then the user has to perform the delete operation.

In this article, I have done both operations on a page using the add and delete buttons.

First, you have to create a project using the command ng new demo.

Creating components and forms

Then open this project with the terminal and add a component using the command ng new c component name. When you create a component using comment then your project automatically registers your component in the module. After adding this component name open this component and create a form in the .html file. After creating a form you have to create a label for showing which message you have to want to print with the text box. Then you have to create a text field where the user enters the details. After creating the text field and the label, you have to create two buttons one button is for submitting the value, and the second button is for deleting the value. and then create a function on the submit and delete button and then close the form.

Then go to the .ts file and then create both functions which function we create in the HTML form. After creating these function user has to create a query for adding and deleting the data. After completing the query, you have to go to the HTML page again and take a div <div></div> and then use a for loop to display the all values on the browser in the div using the key value. After completing this process you have to go to the .css page and modify the view of your application. Then go to the module file and check if all components and dependencies are registered or not.

process.Component.html

<form (submit)="AddTodo()">
    <input
        type="text"
        name="inputTodo"
        placeholder="Enter ToDo Text Here For Test....."
        class="todo-input"
        [(ngModel)]="inputTodo">
    <input type="submit" value="Add Todo" class="todo-submit">
</form>
<div *ngFor="let todo of todos; let i = index;" class="todo {{(todo.completed ? 'done' : '')}}">
    <div class="id">{{i}}</div>
    <div class="content" (click)="toogleDone(i)">{{todo.content}}</div>
    <button class="delete" (click)="deleteTodo(i)">remove</button>
</div>

Now open the .ts file write the code and create the function you have to create on the submit button and delete button. And then create a query in these functions. The code will be shown like this:

process.component.ts

import { Component, OnInit } from '@angular/core';
import { Todo } from './../models/Todo';
@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {
  inputTodo: string = '';
  title = 'todo app';
  todos: Todo[];
  constructor() { }
  ngOnInit(): void {
    this.todos = [
      {
        content: 'first todo',
        completed: false
      },
      {
        content: 'second todo',
        completed: true
      }
    ];
  }
  toggleDone(id: number) {
    this.todos.map((v, i) => {
      if (i == id) v.completed = !v.completed;
      return v;
    });
  }
  deleteTodo(id: number) {
    this.todos = this.todos.filter((v, i) => i !== id);
  }
  AddTodo() {
    this.todos.push({
      content: this.inputTodo,
      completed: false
    });
    this.inputTodo = "";
  }
}

Now add to the CSS to make an attractive view of your project.

component.css

.todo {
  display: flex;
  padding: 10px 15px;
  background-color: #fff;
  border-bottom: 1px solid #dddd;
}
.todo:nth-child(even) {
  background-color: #dddd;
}
.todo:last-of-type {
  border-bottom: 0;
}
.id {
  flex: 1 1 50px;
}
.content {
  flex: 1 1 100%;
  text-decoration: dashed;
}
.todo-input {
  display: block;
  width: 100%;
  padding: 10px 15px;
  appearance: none;
  border: none;
  background-color: #f3f3f3;
  margin-top: 15px;
  font-size: 20px;
  outline: none;
}
.todo-submit {
  display: block;
  width: 100%;
  max-width: 200px;
  appearance: none;
  border: none;
  outline: none;
  background: none;
  background-color: #fe4880;
  color: #fff;
  margin: 15px auto;
  padding: 10px 15px;
  font-size: 18px;
  font-weight: 700;
}

Now go to the app component.html and write the code to display your output on the first.

You have to write the router outlet to render the page you want to first view.

appcomponent.html

<div class="todo">
  <header>
    <h2> Todo List</h2>
  </header>
</div>
<br>
<router-outlet></router-outlet>

appcomponent.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'todo app ';
}

module.ts

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { TodoComponent } from './Todo/todo.component';
import { RegisterComponent } from './register/register.component';
import { SearchComponent } from './search/search.component';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
const routes: Routes = [
  { path: '', component: TodoComponent },
  { path: 'additem', component: RegisterComponent },
  { path: 'search', component: SearchComponent },
  { path: '**', component: TodoComponent }
];
@NgModule({
  declarations: [
    AppComponent,
    TodoComponent,
    RegisterComponent,
    SearchComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    RouterModule.forRoot(routes),
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
  enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

index.ts

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Todo</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
    <app-root></app-root>
</body>
</html>

Now compile this project using the command “ ng serve”. After compiling successfully you have to run this project on the browser using the command “ localhost:4200”. After 1 or 2 seconds, you can see the output like this.

Output

Enter to do text

Now you can see that there are two values that we add to the code. Now you have to add a few values to this application.

Second todo

Now press the add todo button and add more value. After adding more value to the application the output will be shown like this,

First and third todo

Now you can see that there are no values added in the application.

Now delete the value using the remove button.

Second and fourth todo

After deleting some values the output will be shown like this.

After deleting some values

Now you can see that there are only two values. We have deleted the multiple values. and both of our buttons work properly.

I hope you enjoy this article.

To learn more about angular follow me on Chaman Gautam and to learn about more technology follow C# Corner.

Thank you.


Similar Articles