Angular 8 App Crud Operation Tutorial From Scratch

Befor get started with angular 8 crud operation. You must have installed Angular 8 project. If you don’t know how to setup Angular 8 project follow ‘How to Install Angular 8‘ article to setup Angular 8 project.

So let’s get start:

Create Angular 8 Component

What is component?
Components are a logical piece of code for Angular JS application. We will create three component.

Type the following command to generate Angular 8 Components. We will perform create, read, update operations. So we will create three components.

To create it:

ng g component todo
ng g component todoAdd
ng g component todoEdit

Open src/app/app.module.ts you will see all the three components imported and declared in declarations section by Angular 8 itself.

Create Angular 8 Routing

Now We need to create route for the above created component. So when you navigate the route you will be see the html of your component.

To create new route open the “app-routing.module.ts” file under the “your project directory > src > app”.

Import all three above created component to the routing module. Add the below line in the top of the “app-routing.module.ts” file.

import { TodoComponent } from './todo/todo.component';
import { TodoAddComponent } from './todo-add/todo-add.component';
import { TodoEditComponent } from './todo-edit/todo-edit.component';

You will see the route variable. Changed with this

const routes: Routes = [
  {
    path: '',
    component: TodoComponent,
    data: { title: 'List of todos' }
  },
  {
    path: 'todo/add',
    component: TodoAddComponent,
    data: { title: 'Add todo' }
  },
  {
    path: 'todo/edit/:id',
    component: TodoEditComponent,
    data: { title: 'Edit todo' }
  },
];

Install bootstrap 4 CSS Framwork

Next, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, add it inside the angular.json file.

"styles": [
   "src/styles.css",
   "./node_modules/bootstrap/dist/css/bootstrap.min.css"
 ]

So, now we can use the Bootstrap 4 classes in our project.

Configure the Angular 8 Form Validation

We will use ReactiveFormsModule for Angular 8 Form Validation.
Now, import the ReactiveFormsModule inside the app.module.ts file.

import { ReactiveFormsModule } from '@angular/forms';

imports: [
    ReactiveFormsModule
],

Create Todo Class

Now, we create a class like model class.

To create Todo class run the below command

ng g class todo

Now, write all properties of the Todo class related to an todo that matches with the database. Open the todo.ts file and put the below code.

export class Todo {
    id: number;
    title: string;
    updated_at: Date;
}

Modify Angular 8 entry page

Open src/app/app.component.html and modify this HTML page to fit the CRUD page. Replace with the following html

<router-outlet></router-outlet>

Modify todo list component

Open src/app/todo.component.html and put the below html

<div class="container mt-5">
  <h2>Todos
    <a class="float-right" [routerLink]="['/todo/add']">
      <button type="button" class="btn btn-primary">Add</button>
    </a>
  </h2>
  <table class="table table-bordered mt-5">
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of data; let i = index;">
            <td width="20">{{item.id}}</td>
            <td>{{item.title}}</td>
            <td width="250">                
                <button type="button" class="btn btn-danger mr-1" (click)="deleteTodo(item.id, i)">Delete</button>
                <a [routerLink]="['/todo/edit/', item.id]">
                  <button type="button" class="btn btn-primary">Edit</button>
                </a>
            </td>
          </tr>
    </tbody>
  </table>
</div>

Open src/app/todo.component.ts and put the below code

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
import { Todo } from '../todo';

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {

  data: Todo[] = [];

  constructor(private api: ApiService) { }
  

  ngOnInit() {
    this.api.getTodos()
      .subscribe(res => {
        this.data = res;
      }, err => {
        console.log(err);
      });
  }

  deleteTodo(id, index) {
    this.api.deleteTodo(id)
      .subscribe(res => {    
          this.data.splice(index,1);
        }, (err) => {
          console.log(err);
        }
      );
  }
}

Modify todo add component

Open src/app/todo-add.component.html and put the below html

<div class="row mt-5">
  <div class="col-md-6 mx-auto">
      <h2 class="text-center">Add Todo</h2>
      <div class="card mt-3">
          <div class="card-body">
            <form [formGroup]="todoForm" (ngSubmit)="addTodo()">
              <div class="form-group">
                <label class="col-md-4">Title </label>
                <input type="text" class="form-control" formControlName="title" />
              </div>
              <div class="form-group">
                <button type="submit" class="btn btn-primary col-md-4" [disabled]="todoForm.invalid">Add</button>
                <a [routerLink]="['/']">
                  <button type="submit" class="btn btn-primary col-md-4 ml-1">Back</button>
                </a>
              </div>
            </form>
          </div>
      </div>
  </div>
</div>

Open src/app/todo-add.component.ts and put the below code

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import { ApiService } from '../api.service';
import {Router} from "@angular/router";

@Component({
  selector: 'app-todo-add',
  templateUrl: './todo-add.component.html',
  styleUrls: ['./todo-add.component.css']
})

export class TodoAddComponent implements OnInit {
  
  todoForm: FormGroup;
  constructor(private formBuilder: FormBuilder, private router: Router, private api: ApiService) { }


  ngOnInit() {
    this.todoForm = this.formBuilder.group({
      title: ['', Validators.compose([Validators.required])],
    });
  }

  addTodo() {
    const payload = {
      title: this.todoForm.controls.title.value,
    };

    this.api.addTodo(payload)
      .subscribe(res => {
          let id = res['_id'];
          this.router.navigate(['/']);
        }, (err) => {
          console.log(err);
        });
  }
}

Modify todo edit component

Open src/app/todo-edit.component.html and put the below html

<div class="row mt-5">
  <div class="col-md-6 mx-auto">
      <h2 class="text-center">Update Todo</h2>
      <div class="card mt-3">
          <div class="card-body">
            <form [formGroup]="todoForm" (ngSubmit)="updateTodo(todoForm.value)">
              <div class="form-group">
                <label class="col-md-4">Title </label>
                <input type="text" class="form-control" formControlName="title" />
              </div>
              <div class="form-group">
                <button type="submit" class="btn btn-primary col-md-4" [disabled]="todoForm.invalid">Update</button>
                <a [routerLink]="['/']">
                  <button type="submit" class="btn btn-primary col-md-4 ml-1">Back</button>
                </a>
              </div>
            </form>
          </div>
      </div>
  </div>
</div>

Open src/app/todo-edit.component.ts and put the below code

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators, NgForm} from "@angular/forms";
import { ApiService } from '../api.service';
import { ActivatedRoute, Router } from '@angular/router';

import { Todo } from '../todo';

@Component({
  selector: 'app-todo-edit',
  templateUrl: './todo-edit.component.html',
  styleUrls: ['./todo-edit.component.css']
})
export class TodoEditComponent implements OnInit {

  todoForm: FormGroup;
  id:number= null;

  constructor(
    private formBuilder: FormBuilder, 
    private activeAouter: ActivatedRoute, 
    private router: Router, 
    private api: ApiService
  ) { }

  ngOnInit() {
    
    this.getDetail(this.activeAouter.snapshot.params['id']);

    this.todoForm = this.formBuilder.group({
      title: ['', Validators.compose([Validators.required])],
    });
  }

  getDetail(id) {
    this.api.getTodo(id)
      .subscribe(data => {
        this.id = data.id;
        this.todoForm.setValue({
          title: data.title
        });
        console.log(data);
      });
  }
  updateTodo(form:NgForm) {

    this.api.updateTodo(this.id, form)
      .subscribe(res => {
          this.router.navigate(['/']);
        }, (err) => {
          console.log(err);
        }
      );
    
  }

}

Configure the HttpClientModule

We need HttpClientModule to access RESTful API. So before creating a service, first, Open src/app/app.module.ts then add this import.

import { HttpClientModule } from '@angular/common/http';

Add HttpClientModule to imports array under @NgModule

imports: [
    HttpClientModule
]

Create Angular 8 Service for Accessing RESTful API

Generate an Angular 8 service for Accessing RESTful API by typing this command.

ng g service api

Next, open and edit src/app/api.service.ts then add the below imports.

import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Todo } from './todo';

Then create two constants:

const apiUrl = "http://localhost/curd";

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

Next, open and edit src/app/api.service.ts then add the below function.

  getTodos (): Observable<Todo[]> {
    return this.http.get<Todo[]>(apiUrl, httpOptions)
      .pipe(
        tap(heroes => console.log('fetched todos')),
        catchError(this.handleError('getTodos', []))
      );
  }

  getTodo(id: number): Observable<Todo> {
    const url = `${apiUrl}?id=${id}`;
    return this.http.get<Todo>(url).pipe(
      tap(_ => console.log(`fetched todo id=${id}`)),
      catchError(this.handleError<Todo>(`getTodo id=${id}`))
    );
  }
  
  addTodo (todo): Observable<Todo> {
    
    return this.http.post<Todo>(`${apiUrl}/create.php`, todo, httpOptions).pipe(
      tap((todo: Todo) => console.log(`added todo w/ id=${todo.id}`)),
      catchError(this.handleError<Todo>('addTodo'))
    );
  }
  
  updateTodo (id, todo): Observable<any> {
    const url = `${apiUrl}/update.php?id=${id}`;
    return this.http.put(url, todo, httpOptions).pipe(
      tap(_ => console.log(`updated todo id=${id}`)),
      catchError(this.handleError<any>('updateTodo'))
    );
  }
  
  deleteTodo (id): Observable<Todo> {
    const url = `${apiUrl}/delete.php?id=${id}`;
  
    return this.http.delete<Todo>(url, httpOptions).pipe(
      tap(_ => console.log(`deleted todo id=${id}`)),
      catchError(this.handleError<Todo>('deletetodo'))
    );
  }
  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
  
      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead
  
      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

Run the below command, will run the Angular 8 Web Application and open the Application in browser by it self

ng serve -o

The Angular 8 crud operation application will looks like

50 Comments

  1. Ricardo said:

    Hi,
    This code is awesome, do you have the backend part in php ?

    October 16, 2019
    Reply
  2. Jamshid said:

    Hi.
    Do you have the video tutorial of this code?
    If yes please share.
    If no please make and share 🙂

    November 1, 2019
    Reply
  3. sonu kumar said:

    not abel to add data any video for this tutorial

    November 4, 2019
    Reply
  4. astri said:

    i can not add and show the data i have inputted

    November 20, 2019
    Reply
  5. Gowri Sankar Nagaraj said:

    Nice man

    February 26, 2020
    Reply
  6. cbd for pain said:

    Needed to send you the very little word to finally thank you so much the moment again regarding the spectacular techniques you have shared on this site. This has been simply surprisingly open-handed with you to present unreservedly what most of us would’ve sold for an electronic book to help make some money on their own, precisely seeing that you might well have tried it in the event you wanted. Those tactics in addition worked to become great way to realize that someone else have the same keenness similar to my very own to realize significantly more with reference to this problem. I know there are some more pleasurable situations up front for people who scan through your website. https://nfesusmmrn.online/

    January 7, 2021
    Reply
  7. generic tadalafil said:

    I’m also commenting to let you be aware of of the brilliant discovery my child encountered checking the blog. She came to understand a lot of details, including how it is like to have a marvelous coaching character to get folks completely fully grasp a variety of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel. https://hillsdaledowcenter.com/

    January 7, 2021
    Reply
  8. kamagra online said:

    I needed to draft you one little observation so as to say thank you as before for those great methods you’ve documented here. It has been certainly pretty generous of people like you to convey freely exactly what a number of people could possibly have made available as an e book to earn some cash for their own end, even more so considering the fact that you could possibly have done it if you ever decided. The ideas also acted like a fantastic way to comprehend other individuals have similar dreams like my own to grasp good deal more on the subject of this issue. I’m sure there are many more fun occasions ahead for individuals that look into your blog post. https://jlsmithjax.com/

    January 8, 2021
    Reply
  9. buy aripiprazole said:

    I simply wanted to thank you so much once more. I do not know what I would’ve taken care of without these strategies revealed by you over that subject. It was an absolute horrifying matter in my position, nevertheless spending time with this specialized style you resolved the issue took me to leap with happiness. I will be happy for your service and then sincerely hope you realize what an amazing job you have been providing teaching some other people using your web site. Most likely you haven’t got to know any of us. https://abilifyaripiprazoles.com/

    January 8, 2021
    Reply
  10. ziprasidone without a prescription said:

    My husband and i ended up being cheerful Albert could carry out his analysis because of the ideas he acquired from your blog. It’s not at all simplistic just to always be freely giving facts a number of people could have been making money from. And now we acknowledge we’ve got the blog owner to appreciate because of that. All of the explanations you’ve made, the easy blog menu, the friendships you aid to create – it’s all amazing, and it’s aiding our son and our family believe that that article is satisfying, which is certainly unbelievably vital. Thanks for the whole thing! https://geodonziprasidone.com/

    January 8, 2021
    Reply
  11. generic tofranil said:

    My husband and i ended up being contented Chris could carry out his basic research by way of the ideas he came across from your own blog. It’s not at all simplistic just to always be giving away guidelines many others could have been making money from. And now we consider we’ve got the blog owner to appreciate because of that. All the explanations you’ve made, the easy blog menu, the friendships you aid to create – it’s all astounding, and it’s aiding our son and our family consider that that concept is awesome, and that’s exceptionally essential. Many thanks for all! https://tofranilimipramine.com/#

    January 9, 2021
    Reply
  12. quetiapine no rx said:

    I’m commenting to let you be aware of of the beneficial discovery my child developed browsing the blog. She came to find a lot of details, including how it is like to have a great coaching character to get certain people completely comprehend a number of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel. https://seroquelquetiapine.com/#

    January 10, 2021
    Reply
  13. tofranil cheap said:

    My husband and i felt absolutely ecstatic Edward could complete his homework from the ideas he discovered from your very own site. It’s not at all simplistic just to be giving away helpful tips that men and women could have been making money from. And we discover we have the blog owner to appreciate because of that. Most of the explanations you’ve made, the easy blog menu, the friendships you assist to engender – it’s everything excellent, and it’s assisting our son and our family do think that content is brilliant, and that’s extraordinarily fundamental. Many thanks for all the pieces! https://tofranilimipramine.com/#

    January 10, 2021
    Reply
  14. steveclarke said:

    Oh my goodness! Awesome article dude! Thanks, However I am having difficulties with your RSS. I don’t understand the reason why I can’t subscribe to it. Is there anybody having the same RSS issues? Anyone that knows the answer can you kindly respond? Thanks!!
    Life Experience Degrees

    January 12, 2021
    Reply
  15. clarkericky said:

    Hello there, just was aware of your weblog via Google, and found that it’s really informative. I am gonna watch out for brussels. I will be grateful should you proceed this in future. Many people will probably be benefited from your writing. Cheers!| Life Experience Degree

    January 12, 2021
    Reply
  16. https://txt2080.com/ said:

    Its always overlooked skill as most bloggers go on overdrive to link build. Of paramount importance is to understand the post before commenting as always an off topic of general comment is often taken 
    Hope you’re having a great week. Thanks again for commenting, Ahmed.
    카지노사이트

    January 13, 2021
    Reply
  17. https://www.vfv79.com/baca/ said:

    Thanks for the kind words, Ahmed. And thank you so much for sharing the post with your friends and followers.
    And commenting on other blogs isn’t just helpful for new bloggers — it’s helpful for those of us who have been doing it a while, too. All of us want to build relationships. 
    바카라사이트

    January 13, 2021
    Reply
  18. https://liveone9.com/ said:

    Thank you! Yes, I enjoy step-by-step guides, too. They make learning a lot easier.
    After that you could contribute to the community by guest posting. You’ll have much more better results because people are already familiar with you.
    카지노사이트

    January 13, 2021
    Reply
  19. Dorie said:

    always i used to read smaller articles or reviews which also clear their motive, and that
    is also happening with this article which I am reading now.

    Also visit my web-site cheap flights

    January 29, 2021
    Reply
  20. Kristine said:

    Hurrah, that’s what I was searching for, what a information! present here at this website, thanks admin of this site.

    My web blog; cheap flights

    January 29, 2021
    Reply
  21. Lonnie said:

    I am in fact glad to glance at this webpage posts which includes lots of helpful facts, thanks for providing these kinds of information.

    Look at my website cheap flights

    January 30, 2021
    Reply
  22. Hung said:

    I enjoy what you guys are usually up too.

    Such clever work and exposure! Keep up the good works guys I’ve you guys to blogroll.

    Also visit my webpage :: cheap flights

    January 31, 2021
    Reply
  23. Connie said:

    Hi, Neat post. There is an issue together with your web site in internet explorer, may test this?
    IE still is the market chief and a big component to other folks will omit your wonderful writing because of this problem.

    my web page – cheap flights

    February 1, 2021
    Reply
  24. Jaclyn said:

    Every weekend i used to pay a quick visit this web page, as i want enjoyment,
    since this this web site conations actually nice funny material too.

    Feel free to visit my blog post – cheap flights – tinyurl.com,

    February 2, 2021
    Reply
  25. Christine said:

    Hello, its pleasant post about media print, we all know media is
    a wonderful source of information.

    My blog – cheap flights

    February 2, 2021
    Reply
  26. Rashad said:

    whoah this weblog is fantastic i love reading your articles.
    Stay up the good work! You realize, a lot of persons are looking round
    for this information, you could aid them greatly.

    My website … cheap flights (tinyurl.com)

    February 3, 2021
    Reply
  27. Kbcxbype said:

    best online pharmacies no prescription panacea pharmacy fda approved canadian online pharmacies

    February 5, 2021
    Reply
  28. Ahkdguany said:

    north west pharmacy canada ed drugs canada prescription drugs

    February 5, 2021
    Reply
  29. Jbnbbluch said:

    canadian pharmacies top best online pharmacies prescription without a doctor’s prescription

    February 7, 2021
    Reply
  30. FvfcGeste said:

    online pharmacies in usa 50mg viagra where can i order viagra super forse

    February 8, 2021
    Reply
  31. Labxguany said:

    what’s the difference between levitra and cialis cialis cagliari dosering av cialis

    February 11, 2021
    Reply
  32. Tamie said:

    This website certainly has all the information I needed concerning this subject and didn’t know who to ask.

    Also visit my blog; cheap flights (tinyurl.com)

    February 12, 2021
    Reply
  33. Jbnvbluch said:

    petty cash advance receipt form payday loans via sms payday loan lenders guaranteed approval

    February 14, 2021
    Reply
  34. Mia said:

    Invisible Man Is It Scary Elementary Education Level 1

    Also visit my page pdf base

    February 16, 2021
    Reply
  35. Madeline said:

    Michael Connelly Books Void Moon My Brilliant Friend James
    Wood

    Here is my web site … wordpress pdf (canoportra1984.netlify.app)

    February 17, 2021
    Reply
  36. Donaldcep said:

    Very nice quality article

    free robux

    February 17, 2021
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *