Routing, Validation, And Delete Operations In Angular 2

If you missed any of the previous articles, you can read them  here:

In this third part of the tutorial, I am going to cover the topics give below.

  • Creating Routing
  • Add
  • Validation
  • Delete
  • Update and more

At the end of the article, you will find the link to the source code on GitHub, so feel free to play with the code yourself.

In part 1, I created RESTful API, using node.js and MySQL. In part 2, I discussed the read operation and also how to create custom filter pipe etc.

Now, in this article I am starting from routing.

Creating Routing

Angular2 routing is all about the changing state of your Application and loading different components which depend on the URL that the user enters. Angular 2 first parses the URL entered by the user, identifies the routes and then finally loads the suitable component.

How does routing work?

Angular2

First, I am creating the router array.

  1. [code language=”typescript”]  
  2. app.routing.ts  
  3. import {  
  4.   Routes,RouterModule;  
  5. }  
  6.   
  7. from '@angular/router';  
  8. import {  
  9.   TasksComponent;  
  10. }  
  11.   
  12. from './tasks/tasks.component';  
  13. import {  
  14.   AddtasksComponent;  
  15. }  
  16.   
  17. from './tasks/addtasks.component';  
  18. const routerRoutes=[ {  
  19.   path'',redirectTo'/allTask',pathMatch'full';  
  20. },  
  21. {path'allTask',componentTasksComponent;  
  22. },  
  23. {path'addTask',componentAddtasksComponent;  
  24. }  
  25.   
  26. ];  
  27. export const routes=RouterModule.forRoot(router);  
  28. [/code]  
Thus, in the code above, I had imported Routes and RouterModule from @angular/router and created one const array, which is named as a router. Inside the array, I created the routing paths. For example, if the user does not enter anything in the URL, which is http//localhost4200/. It will redirect to ‘/allTask’ and it will load the tasks.component.

After creating the routing file, it must be declared in imports array in app.module.ts
  1. [code language = ”typescript”]  
  2. imports[  
  3.     BrowserModule,  
  4.     FormsModule,  
  5.     HttpModule,  
  6.     routes  
  7.   ], [/code]  
Now, the third step for routing to perform in Angular 2 is setting up the router-outlet in app.component.html, which is the route component of my project.
  1. [code language = ”html”] < router - outlet > < /router-outlet> [/code]  
Now, on loading of the root component, it will directly go to app.routing.ts file and depending on the URL requested by the user, the component will be loaded..

Now, we need routing on each and every page. Thus, for my convenience, I am creating one component as a header.component in which I will create a menu for my project. I am using Bootstrap to design the menu.

Header.component.html
  1. [code language=”html”]  
  2.   
  3. <nav class="navbar navbar-inverse">  
  4.   <div class="container-fluid">  
  5.     <!-- Brand and toggle get grouped for better mobile display -->  
  6.     <div class="navbar-header">  
  7.       <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">  
  8.         <span class="sr-only">Toggle navigation</span>  
  9.         <span class="icon-bar"></span>  
  10.         <span class="icon-bar"></span>  
  11.         <span class="icon-bar"></span>  
  12.       </button>  
  13.       <a class="navbar-brand" routerLink="/allTask">CsharpCorner</a>  
  14.     </div>  
  15.     <!-- Collect the nav links, forms, and other content for toggling -->  
  16.     <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">  
  17.       <ul class="nav navbar-nav">  
  18.         <li class="active">  
  19.           <a routerLink="/allTask">Task   
  20.             <span class="sr-only">(current)</span>  
  21.           </a>  
  22.         </li>  
  23.         <li>  
  24.           <a routerLink="/addTask">AddTask</a>  
  25.         </li>  
  26.       </ul>  
  27.     </div>  
  28.     <!-- /.navbar-collapse -->  
  29.   </div>  
  30.   <!-- /.container-fluid -->  
  31. </nav>   
  32. [/code]  
In HTML given above ,

Focus on <a routerLink="/addTask">AddTask</a>. Now, as Angular2 has done all routing locally, so we will be using router link instead of href.

Add New Task

In this demo, I am using two way data binding for the add operation. You can get an idea about data binding from here.

addtasks.component.html
  1. [code language=”html”]  
  2.   
  3. <div class="row">  
  4.   <app-header></app-header>  
  5. </div>  
  6. <div class="container">  
  7.   <form (ngSubmit)="taskSubmit()" #addform="ngForm">  
  8.     <div class="form-group">  
  9.       <label for="id">Id</label>  
  10.       <input type="number" [(ngModel)]="model.Id"   
  11. name="id"   
  12. class="form-control" id="id"  
  13. required #id="ngModel">  
  14.       </div>  
  15.       <div [hidden]="id.valid || id.pristine"   
  16. class="alert alert-danger">  
  17. Task Id is required  
  18. </div>  
  19.       <div class="form-group">  
  20.         <label for="name">Task</label>  
  21.         <input type="text" [(ngModel)]="model.Title"   
  22. name="title"   
  23. class="form-control" id="name"  
  24. required #title="ngModel">  
  25.         </div>  
  26.         <div [hidden]="title.valid || title.pristine"   
  27. class="alert alert-danger">  
  28. Task Title is required  
  29. </div>  
  30.         <div class="form-group">  
  31.           <label for="power">Status</label>  
  32.           <select class="form-control" id="status"   
  33. [(ngModel)]="model.Status" name="status"  
  34. required>  
  35.             <option *ngFor="let s of status" [value]="s">{{s}}</option>  
  36.           </select>  
  37.         </div>  
  38.         <button type="submit" class="btn btn-default form-control" [disabled]="!addform.form.valid" >Add Task</button>  
  39.       </form>  
  40.     </div>  
  41. [code]  
In the above html, I called the <app-header></app-header> component for the menu which I had created previously and also created #addform variable which is the reference to the <form > itself. On Clicking of button I checked for form’s state and whether it is valid or not. If all the validations inside the form are validated then the form will be valid, otherwise the form will be in an invalid state. Depending on the form’s state I am enabling the button.
  1. [code language=”html”]  
  2. <button type="submit" class="btn btn-default form-control" [disabled]="!addform.form.valid" >Add Task</button>  
  3. [/code]  
As I said I am using two way data-binding for add operation, I will create the model object on addtasks.component.ts and bind it with different controls so that when I change the values from controls it will automatically change in the model.
  1. [code language=”html”]  
  2. <input type="number" [(ngModel)]="model.Id"   
  3. name="id"   
  4. class="form-control" id="id"  
  5. required #id="ngModel">  
  6. [/code]  
So with the [(ngModel)]=”model.Id”, when I am changing the value in input box it will also reflects in model object in addtasks.component.ts file.

I had used dropdown for Status field (done or pending), so I will create an array of string in typescript file and loop through it and bind it to html page.
  1. [code language=”html”]  
  2.   
  3. <select class="form-control" id="status"   
  4. [(ngModel)]="model.Status" name="status"  
  5. required>  
  6.   <option *ngFor="let s of status" [value]="s">{{s}}</option>  
  7. </select>  
  8. [/code]  
addtasks.component.ts
  1. [code language=”typescript”]  
  2. import { Component, OnInit } from '@angular/core';  
  3. import { Router } from '@angular/router';  
  4. import { TaskdataService } from '../shared/taskdata.service';  
  5.   
  6. @Component({  
  7. selector 'app-addtasks',  
  8. templateUrl './addtasks.component.html',  
  9. styles []  
  10. })  
  11. export class AddtasksComponent implements OnInit {  
  12. statusstring[]=[  
  13. 'done',  
  14. 'pending'  
  15. ];  
  16. model = {Id'',Title'',Status'pending'};  
  17. constructor(private _taskdataTaskdataService,private _routerRouter) { }  
  18. ngOnInit() {  
  19. }  
  20. taskSubmit()  
  21. {  
  22. this._taskdata.addTask(this.model)  
  23. .subscribe(  
  24. (dataany)=>{  
  25. console.log(data);  
  26. this._router.navigate(['/allTask']);  
  27. },  
  28. function(error){  
  29. console.log(error);  
  30. },  
  31. function(){  
  32. console.log('complete');  
  33. }  
  34. );  
  35. }  
  36. }  
  37. [/code]  
Here in above code as I said i created the Status array of type string and model object which can hold Id,Title,Status.

On click of add task button I am calling the taskSubmit() function inn which I am calling addtask method which I created in taskdata.service.

Subscribe method will take three arguments first is on success, second on error, third on complete.

Angular2

Angular2

Delete Task

Now for delete task ,I will simply add one button inside the tasks.component.html which I created previous article.
  1. [code language=”html”]  
  2.   
  3. <button (click)='deleteStatus(item)' type="button" class="btn btn-default" aria-label="Left Align">  
  4.   <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>  
  5. </button>  
  6. [/code]  
Here I create the click event for delete button on which I am calling the deleteStatus method.
  1. [code language=”typescript”]  
  2. deleteStatus(itemTask){  
  3. this._taskdata.deleteTask(item.Id)  
  4. .subscribe(  
  5. (dataany)=>{  
  6. this.allTasks.splice(this.allTasks.indexOf(item),1);  
  7. },  
  8. function(error){  
  9. console.log(error);  
  10. },  
  11. function(){  
  12. console.log(‘complete’);  
  13. }  
  14. );  
  15. }  
  16. [/code]  
On success I am simply removing the record from the array as page will not post back.

Update Task


Now on update I simply created the toggle button i.e. it will change the status to done or pending.
  1. [code language=”html”]  
  2.   
  3. <button (click)='updateStatus(item)' type="button" class="btn btn-default" aria-label="Left Align">  
  4.   <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>  
  5. </button>  
  6. [/code]  
Here I create the click event for update button on which I am calling the updateStatus method.
  1. [code language=”typescript”]  
  2. updateStatus(itemTask){  
  3. this._taskdata.editTask(item)  
  4. .subscribe(  
  5. (dataany)=>{  
  6. if(item.Status=="done")  
  7. {  
  8. item.Status='pending';  
  9. }  
  10. else  
  11. {  
  12. item.Status='done';  
  13. }  
  14. },  
  15. function(error){  
  16. console.log(error);  
  17. },  
  18. function(){  
  19. console.log ('Edited successfully');  
  20. }  
  21. );  
  22. }  
  23. [/code]  
Summary

We covered a lot in this tutorial. Let’s just summarize it.

 

  • Routing
  • Validation
  • Add
  • Delete
  • Update and more

There is a lot more to come in the next tutorial (Multiple delete,file upload,pagging). So, stay tuned for more.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now