Angular 7/8 Tutorial with Bootstrap 4 | Learn Angular using Basic CRUD Example

by Sam  


Angular, formerly known as AngularJS, is one of the leading javascript frameworks along with ReactJS and VueJS. With the use of this framework, you can do a lot of front-end stuffs faster.

The purpose of this tutorial is to help you implement CRUD (Create, Read, Update and Delete) operation using an angular app. I anticipate that you have already prior knowledge in Javascript, HTML, CSS, basic typescript.

Let’s get started


1. Requirements

Before going through the steps below, you have to make sure that you have installed the following:

Angular CLI
NPM
Node 10 or higher

To verify, you may open your terminal (command prompt in windows) and execute the commands below:

$ ng --version
$ npm --version
$ node --version

2. Create angular app

Let’s start creating an angular application. From your terminal, execute the commands below:

$ ng new basic-crud --routing

Notice that we added --routing during creating of an angular app. This command automatically adds app-routing.module.ts file which you will see inside the project folder.

$ cd basic-crud
$ ng serve

Let’s navigate to basic-crud folder and start the app. Sometimes, you would prefer to use ng serve -o in order to open the browser for you automatically.

Now, go to the browser and type: http://localhost:4200

3. Install Bootstrap 4

Angular has a design template called angular material. But, to make it simple, let’s just use bootstrap 4 in this tutorial.

Open a new terminal and install bootstrap.

$ npm install bootstrap --save

After installing the bootstrap, we can now use it in our angular application.

Go to angular.json and add the bootstrap.min.css.

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

Next, open styles.scss and import bootstrap.css.

@import "~bootstrap/dist/css/bootstrap.css";

4. Add Components

Let’s generate the needed components for our CRUD application.

$ ng g c components/post-list
$ ng g c components/post-add
$ ng g c components/post-update

The commands above will create components folder inside src/app. Let’s just have to make our components organize.

5. Configure Routing

Next, let’s customize the routing. Open app-routing.module.ts and modify with code below:

...
import { PostListComponent } from './components/post-list/post-list.component';
import { PostAddComponent } from './components/post-add/post-add.component';
import { PostUpdateComponent } from './components/post-update/post-update.component';
...
const routes: Routes = [
{ path:'posts', component: PostListComponent},
{ path:'post/add', component: PostAddComponent},
{ path:'post/update/:id', component: PostUpdateComponent },
{ path:'', component: PostListComponent}
];
...

From the paths above, we set the PostListComponent as the default route. It means it serves as the homepage of our application.

6. Add Navigation in app.component.html

Since we added bootstrap above, we can use bootstrap styles/classes now. In this case, let’s add navigation inside app.component.html.

<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" routerLink="/">MyApp</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" routerLink="">Lists <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="post/add">Add Post</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<router-outlet></router-outlet>
</div>
</div>

We have to put the navigation inside the app.component.html in order to view the header in any route.

7. Create service

We’re going to display the data into our components, but, it is not good to fetch data into it. Hence, we use services in angular to handle this functionality. So, let’s add posts service:

$ ng g s services/posts --skipTests

We put --skipTest in order to remove the test file. We don’t want it now. For previous versions of angular, it uses –specs

then, add HttpClientModule inside app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';
...
imports: [
HttpClientModule,
]
...

8. Create typescript model

Create a folder models inside app and create Posts.ts file.

export interface Posts{
id: Number;
title: String;
body: String;
}

9. CRUD Implementation

Now let’s start our CRUD.

For the sake of this tutorial, let’s use fake data (jsonplaceholder).

9.1 Add Post (CREATE)

Angular has two different approaches of handling forms. First is Template-driven and another is Reactive Forms. For simple form data, you may use template-drive, but for more complex, it is better to use ReactiveForms. You may check the documentation for further information about the two.

For this tutorial, we’ll use ReactiveForm. Open app.module.ts and add the following:

...
import { ReactiveFormsModule } from '@angular/forms';
...
imports: [
ReactiveFormsModule,
]
...

Open components/post-add.component.html and modify:

<div class="container">
<h1>Add Post</h1>
<form [formGroup]="frm" (ngSubmit)="submitPost($event)">
<label>Title : </label><br>
<input type="text" placeholder="Title" formControlName="title" class="form-control"><br>
<label>Body : </label><br>
<textarea placeholder="Type the body of Post here" formControlName="body" class="form-control" rows="10"></textarea><br><br>
<button type="submit" class="btn-primary">Submit</button>
</form>
</div>

Next, open components/post-add.component.ts

...
import { PostsService } from 'src/app/services/posts.service';
...
export class PostAddComponent implements OnInit {
frm = new FormGroup({
title: new FormControl(''),
body: new FormControl('')
});
constructor(private service: PostsService) { }
ngOnInit() {}
submitPost(e) {
e.preventDefault();
let params = {
title: this.frm.get('title').value,
body: this.frm.get('body').value
};
this.service.postData(params).subscribe(response => {
console.log(response);
});
}
}

Then, let’s add data into services/posts.service.ts

...
import { Observable } from 'rxjs';
import { Posts } from '../models/Posts';
import { HttpClient } from '@angular/common/http';
...
export class PostsService {
JSON_URL = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) { }
getAllPosts(): Observable<Posts>{
return this.http.get<Posts>(this.JSON_URL);
}
postData(params: any): Observable<Posts>{
return this.http.post<Posts>(this.JSON_URL, { params } );
}
updatePost(id: Number, params: Object = {}): Observable<Posts>{
let url = `${this.JSON_URL}/${id}`;
console.log(url);
return this.http.put<Posts>(url, { params});
}
deletePost(id: Number){
let url = `${this.JSON_URL}/${id}`;
return this.http.delete(url);
}
}

We added all of the methods in our services above for CRUD operation.

Now, let’s check our Add post form. Go to http://localhost:4200/post/add. After populating the data and submitting the form, you should see the response into the firebug/console.

Take note that We did not put validation on this tutorial. You may add Validator if you wish to have it.

9.2 Display Posts (READ)

Open components\post-list.component.html and add the codes below:

<div class="container">
<h1>Posts</h1>
<table class="table" *ngIf="show; else showLoading">
<tr>
<td>ID</td><td>Title</td><td>Body</td>
</tr>
<tr *ngFor="let p of posts">
<td>{{ p.id }}</td>
<td>{{ p.title }}</td>
<td>{{ p.body }}</td>
</tr>
</table>

<ng-template #showLoading>
Loading...
</ng-template>
</div>

Next, go to components/post-list.component.ts

...
import { PostsService } from 'src/app/services/posts.service';
...
export class PostListComponent implements OnInit {
show: boolean = false;
posts: Object;
constructor(private service: PostsService) { }
ngOnInit() {
this.getAllPosts();
}
getAllPosts(){
this.service.getAllPosts().subscribe(data => {
this.posts = data;
this.show = true;
});
}
}

We added show attribute to determine if the application is done fetching data from the remote API.

9.3 Update Post (UPDATE)

Let’s modify components/post-list.component.html and add let’s link to a record so that the user can select the post he wanted to update.

...
<table class="table" *ngIf="show; else showLoading">
<tr>
<td>ID</td><td>Title</td><td>Body</td>
</tr>
<tr *ngFor="let p of posts">
<td>{{ p.id }}</td>
<td><a routerLink="post/update/{{ p.id }}">{{ p.title }}</a></td>
<td>{{ p.body }}</td>
</tr>
</table>
...

Next, open components/post-update.component.html and add the code below:

<div class="container">
<h1>Update Post</h1>
<form [formGroup]="frm" (ngSubmit)="updatePost($event)">
<label>Title : </label><br>
<input type="text" placeholder="Title" formControlName="title" class="form-control"><br>
<label>Body : </label><br>
<textarea placeholder="Type the body of Post here" formControlName="body" class="form-control" rows="10"></textarea><br><br>
<button type="submit" class="btn-primary">Submit</button>
</form>
</div>

And then, open components/post-update.component.ts

...
import { FormGroup, FormControl} from '@angular/forms';
import { PostsService } from 'src/app/services/posts.service';
import { ActivatedRoute } from '@angular/router';
...
export class PostUpdateComponent implements OnInit {
frm = new FormGroup({
title: new FormControl(''),
body: new FormControl('')
});
postId: Number = 0;
constructor(private service: PostsService,private route: ActivatedRoute ) { }
ngOnInit() {
this.route.paramMap.subscribe(params => {
this.postId = parseInt(params.get('id'));
});
}
updatePost(e) {
e.preventDefault();
let params = {
title: this.frm.get('title').value,
body: this.frm.get('body').value
};
this.service.updatePost(this.postId, params).subscribe(response => {
console.log(response);
});
}
}

In update, we need to get the current Id number to be updated. From the routing, we passed the :id and we get it here using ActivatedRoute.

9.4 Delete Post (DELETE)

Lastly, we have to execute delete. Just like with update, let’s modify the table list inside components/post-list.component.html.

<table class="table" *ngIf="show; else showLoading">
<tr>
<td>ID</td><td>Title</td><td>Body</td><td>Delete</td>
</tr>
<tr *ngFor="let p of posts">
<td>{{ p.id }}</td>
<td><a routerLink="post/update/{{ p.id }}">{{ p.title }}</a></td>
<td>{{ p.body }}</td>
<td><button class="btn btn-sm btn-danger" (click)="deletePost(p.id)">Delete</button></td>
</tr>
</table>

Next, let’s add deletePost(id: Number) inside the components/post-list.component.ts

export class PostListComponent implements OnInit {
...
deletePost(id: Number){
this.service.deletePost(id).subscribe(data => {
console.log(data);
});
}
...
}

Conclusion

I hope you’ll be able to execute the basic CRUD tutorials above.

If you need of the github repository about this link, don’t hesitate to contact us.

Feel free to comment below.



Leave a Reply

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


Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote