Angular
Let’s get
practical by creating a simple todo app first.
Installations:
Install Visual
Studio Code as code editor
Install
nodejs and NPM
Install
Angular CLI
npm install -g @angular/cli
ng new todo-apps
Visual studio folder has the following contents now:
To run the
app, call :
Ng serve –open
The --open
(or just -o
) option automatically opens your browser to http://localhost:4200/
.
Reference taken from https://angular.io/guide/setup-local
Here is the goal what we want to achieve:
Create a new component todolist:
ng generate component todolist
Todolist component needs a list
of todo tasks. Hence lets create a model for the list:
Create a file “model.ts” in a folder modals inside App folder
export class
Model
{
user:string;
items:any;
constructor()
{
this.user
= "Adam";
this.items
= [new TodoItem("Buy
Flowers", false),new
TodoItem("Get
Shoes", false),
new TodoItem("Collect
Tickets", true),
new TodoItem("Call
Joe", false)]
}
}
export class
TodoItem
{
action;
done;
constructor(action:
string, done:
boolean)
{
this.action
= action;
this.done
= done;
}
}
TODO List is comprised of a set a TODOItems.
So, each ToDoItem has two properties action and done (Boolean).
Now time to design Template (HTML side of it). Copy the following code
into todolist.component.html
<h3 class="bg-primary
p-a-1">{{getUserName()}}'s
To Do List</h3>
<div
class="m-t-1
m-b-1">
<input
class="form-control"
#todoText />
<button
class="btn
btn-primary m-t-1" (click)="addItem(todoText.value)">
Add
</button>
</div>
<table
class="table
table-striped table-bordered">
<thead>
<tr><th></th><th>Description</th><th>Done</th></tr>
</thead>
<tbody>
<tr
*ngFor="let
item of getTodoItems(); let i = index">
<td>{{
i + 1 }}</td>
<td>{{
item.action }}</td>
<td><input
type="checkbox"
[(ngModel)]="item.done"
/></td>
<td
[ngSwitch]="item.done">
<span
*ngSwitchCase="true">Yes</span>
<span
*ngSwitchDefault>No</span>
</td>
</tr>
</tbody>
</table>
Now, need to add the following code in TS file to support the class
methods called in above HTML file.
import { Component,
OnInit } from
'@angular/core';
import { Model,
TodoItem } from
'../modals/model';
@Component({
selector:
'app-todolist',
templateUrl:
'./todolist.component.html',
styleUrls:
['./todolist.component.scss']
})
export class
TodolistComponent
implements OnInit
{
model
= new Model();
constructor()
{ }
ngOnInit():
void {
}
getTodoItems(){
return
this.model.items.filter(item
=> !item.done);
}
getUserName(){
return
this.model.user;
}
addItem(newItem:string)
{
this.model.items.push(new
TodoItem(newItem,
false));
}
}
No comments:
Post a Comment