Sunday, 10 February 2019

How to create To do application

To create “To do app”, first create the basic angular application using the following link https://angulardive.blogspot.com/2019/02/first-angular-application.html
Since we will use Bootstrap, we need to install bootstrap and jquery using following angular-cli command


npm install bootstrap
npm install jquery

Above command add the bootstrap and jquery library in node_modules folder.
We can reference the bootstrap stylesheet in our application either by specifying it in angular.json file in styles array or link in html file or import in styles.css file as follows:

1. bootstrap.min.css speficied in styles array in angular.json
"styles": [
"./node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css
],

2. bootstrap.min.css specified in index.html file   
link rel="stylesheet" type="text/css" href="../node_modules/bootstrap/dist/css/bootstrap.min.css" />

3. bootstrap.min.css specified in styles.css
@import url("../node_modules/bootstrap/dist/css/bootstrap.min.css");

Let’s create a Todo application. It contains a textbox where we enter the tasks and a button to add in tasks list. A list to show all the added tasks. Each item in list contains delete task button to delete added task.

Let’s create a form.


To create the above form, write the following html code in app.component.html

app.component.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<div class="container col-md-5">
  <div>
    <form>
      <div class="form-group">
        <div class="input-group">
          <input type="text" class="form-control" placeholder="Add task" name="task" id="task">
          <button type="button" class="btn btn-labeled btn-primary ml-2">Add <span class="btn-label">
<i class="fa fa-plus-circle" aria-hidden="true"></i>
 </span>
    </button>
        </div>
      </div>     
    </form>
  </div>
</div>

For styling the form apply CSS to the form. So, write following CSS in app.component.css

app.component.css

body{
 padding: 0;
 margin: 0;
}
form{
 max-width: 30em;
 margin: 4em auto;
 position: relative;
 background: #f4f4f4;
 padding: 2em 3em;
}

form input[type=text]::placeholder{
   font-family: "Arial";
   color:#666;
}
form .form-control{
 height: 3em;
    font-family: " Arial ";
}
form .form-control:focus{
 box-shadow: 0;
}

Now our form is created. Let’s add event to the form to add task, display them in a list and delete a task. To do that lets modify and add some new html to app.component.html.

app.component.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<div class="container col-md-5">
  <div>
    <form>
      <div class="form-group">
        <div class="input-group">
          <input type="text" class="form-control" placeholder="Add task" name="task" id="task" [(ngModel)]="task">
          <button type="button" class="btn btn-labeled btn-primary ml-2" (click)="addTask()">Add <span class="btn-label"><i
                class="fa fa-plus-circle" aria-hidden="true"></i></span>
    </button>
        </div>
      </div>
      <div class="data">
          <ul class="list-instyled">
            <li *ngFor="let task of taskArray">{{task}} <i class="fa fa-trash float-right" (click)="deleteTask(task)"></i></li>
          </ul>
      </div>
    </form>
  </div>
</div>

In the above html, the newly added html is shown in italic and events are displayed in bold letter. In angular event is written in parenthesis like (click). For two way binding we have used [(ngModel)] which is bind to a variable task declared in app.component.ts. We have used *ngFor structural directive to loop through the tasks added to an array named taskArray. Since we are using ngModel so we need to import FormsModule in app.module.ts otherwise error will be thrown in console. Below is the app.module.ts where import of FormsModule is shown in bold letter.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

For styling of list to display tasks list, write following CSS in app.component.css

app.component.css

form .data{
    margin-top: 1em;
}
form .data ul{
    padding: 0px!important;
}
form .data li{
 background: #fff;
 border-left: 4px solid red;
 margin: 1em auto;
 color: #666;
 font-family: "Arial";
 padding: 1em;
 list-style: none;
}
form .data li i{
    float: right;
    color: #888;
    cursor: pointer;
}

Since we have used font-awesome in html to display plus and trash icon so use following angular-cli command to install font-awesome.

npm install font-awesome

import font-awesome.min.css in Styles.css as follows:

@import url("../node_modules/font-awesome/css/font-awesome.min.css");

      Now our UI part is done. Let’s handle event in app.component.ts. In the below code we have declared a variable task of string type and an array taskArray. We have created a function addTask() to handle event of Add button. This function add task to taskArray using array object’s push method and clear the value in the textbox. Since we have used two way binding so, if we clear the value of task variable it will be reflected in the textbox. To handle delete event, we have created deleteTask() method which takes task object passed to this method from html. Here we are looping through the taskArray and if the matching task found, we are removing it from array using splice method of array object.

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'To do app';
  task: string = '';
  taskArray = [];

  addTask() {
    this.taskArray.push(this.task);
    this.task = '';
  }

  deleteTask(task) {
    for (let i = 0; i <= this.taskArray.length; i++) {
      if (task == this.taskArray[i]) {
        this.taskArray.splice(i, 1)
      }
    }
  }
}


This post helps you to understand following:
1. How to install packages.
2. How to reference css file.
3. How to attach events to DOM in angular.
4. How to apply two way binding using ngModel
5. How to import modules in app.module.ts
6. How to handle events in TS file.

I hope you enjoyed. In case of any doubt, please comment. Any suggestion is also welcome to improve the further post.

Thanks.


Complete Code


app.component.html

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
</div>
<div class="container col-md-5">
  <div>
    <form>
      <div class="form-group">
        <div class="input-group">
          <input type="text" class="form-control" placeholder="Add task" name="task" id="task" [(ngModel)]="task">
          <button type="button" class="btn btn-labeled btn-primary ml-2" (click)="addTask()">Add <span class="btn-label"><i
                class="fa fa-plus-circle" aria-hidden="true"></i></span></button>
        </div>
      </div>
      <div class="data">
          <ul class="list-instyled">
            <li *ngFor="let task of taskArray">{{task}} <i class="fa fa-trash float-right" (click)="deleteTask(task)"></i></li>
          </ul>
      </div>
    </form>
  </div>
</div>

app.component.css

body{
 padding: 0;
 margin: 0;
}
form{
 max-width: 30em;
 margin: 1em auto;
 position: relative;
 background: #f4f4f4;
 padding: 2em 3em;
}
form input[type=text]::placeholder{
   font-family: "Arial";
   color:#666;
}
form .form-control{
    height: 3em;
    font-family: "Arial";
}
form .form-control:focus{
    box-shadow: 0;
}
form .data{
    margin-top: 1em;
}
form .data ul{
    padding: 0px!important;
}
form .data li{
 background: #fff;
 border-left: 4px solid red;
 margin: 1em auto;
 color: #666;
 font-family: "Arial";
 padding: 1em;
 list-style: none;
}
form .data li i{
    float: right;
    color: #888;
    cursor: pointer;
}


app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule, FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'To do app';
  task: string = '';
  taskArray = [];

  addTask() {
    this.taskArray.push(this.task);
    this.task = '';
  }

  deleteTask(task) {
    for (let i = 0; i <= this.taskArray.length; i++) {
      if (task == this.taskArray[i]) {
        this.taskArray.splice(i, 1)
      }
    }
  }
}


2 comments: