Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

SDM INSTITUTE OF TECHNOLOGY, UJIRE

(Affiliated to VTU, Belgaum, Approved by AICTE, New Delhi)

DEPARTMENT OF CSE/IS/ADE

Angular JS and Node JS


(21CSL581)
Semester 5

Prepared by,
Mr. Adarsh Karanth

Dept. of CSE, SDMIT Page


1
Table of Contents
Syllabus ............................................................................................................................................ 4
Lab Program #1 – Full Name............................................................................................................. 6
Objective ....................................................................................................................................... 6
Steps ............................................................................................................................................. 6
Files .............................................................................................................................................. 6
Code.............................................................................................................................................. 6
Verification .................................................................................................................................... 8
Explanation ................................................................................................................................... 8
Lab Program #2 – Shopping .............................................................................................................. 9
Objective ....................................................................................................................................... 9
Steps ............................................................................................................................................. 9
Files .............................................................................................................................................. 9
Code.............................................................................................................................................. 9
Verification .................................................................................................................................. 10
Explanation ................................................................................................................................. 10
Lab Program #3 – Calculator ........................................................................................................... 12
Objective ..................................................................................................................................... 12
Steps ........................................................................................................................................... 12
Files ............................................................................................................................................ 12
Code............................................................................................................................................ 12
Verification .................................................................................................................................. 13
Explanation ................................................................................................................................. 13
Lab Program #4 – Factorial & Square .............................................................................................. 15
Objective ..................................................................................................................................... 15
Steps ........................................................................................................................................... 15
Files ............................................................................................................................................ 15
Code............................................................................................................................................ 15
Verification .................................................................................................................................. 16
Explanation ................................................................................................................................. 16
Lab Program #5 – Students List ....................................................................................................... 17
Objective ..................................................................................................................................... 17
Steps ........................................................................................................................................... 17
Files ............................................................................................................................................ 17
Code............................................................................................................................................ 17

2|Pa ge
Angular JS and Node JS (21CSL581)
Verification .................................................................................................................................. 19
Explanation ................................................................................................................................. 19
Lab Program #6 – To-Do list ........................................................................................................... 20
Objective ..................................................................................................................................... 20
Steps ........................................................................................................................................... 20
Files ............................................................................................................................................ 20
Code............................................................................................................................................ 20
Verification .................................................................................................................................. 22
Explanation ................................................................................................................................. 22
Appendix ........................................................................................................................................ 23
Commands .................................................................................................................................. 23
Softwares and Installation ............................................................................................................ 23

3|Pa ge
Angular JS and Node JS (21CSL581)
Syllabus
Angular JS & Node JS

Course Code 21CSL581 CIE Marks 50


Teaching Hours/Week (L:T:P: S) 0:0:2:0 SEE Marks 50
Credits 01 Total marks 100
Examination type (SEE) PRACTICAL
Course objectives:
• To learn the basics of Angular JS framework.
• To understand the Angular JS Modules, Forms, inputs, expression, data bindings and Filters
• To gain experience of modern tool usage (VS Code, Atom or any other] in developing Web
applications
Sl.NO Lab Programs/Experiments
1 Develop Angular JS program that allows user to input their first name and last name and display their
full name. Note: The default values for first name and last name may be included in the program.
2 Develop an Angular JS application that displays a list of shopping items. Allow users to add and remove
items from the list using directives and controllers.Note: The default values of items may be included
in the program.
3 Develop a simple Angular JS calculator application that can perform basic mathematical operations
(addition, subtraction, multiplication, division) based on user input.
4 Write an Angular JS application that can calculate factorial and compute square based on given user
input.
5 Develop AngularJS application that displays a details of students and their CGPA. Allow users to read
the number of students and display the count. Note: Student details may be included in the program.
6 Develop an AngularJS program to create a simple to-do list application. Allow users to add, edit, and
delete tasks.Note: The default values for tasks may be included in the program.
7 Write an AngularJS program to create a simple CRUD application (Create, Read, Update, and Delete)
for managing users.
8 DevelopAngularJS program to create a login form, with validation for the username and password
fields.
9 Create an AngularJS application that displays a list of employees and their salaries. Allow users to
search for employees by name and salary. Note: Employee details may be included in the program.
10 Create AngularJS application that allows users to maintain a collection of items. The application
should display the current total number of items, and this count should automatically update as items
are added or removed. Users should be able to add items to the collection and remove them as needed.
Note: The default values for items may be included in the program.
11 Create AngularJS application to convert student details to Uppercase using angular filters.
Note: The default details of students may be included in the program.
12 Create an AngularJS application that displays the date by using date filter parameters
NOTE: Include necessary HTML elementsand CSS for the above Angular applications.

4|Pa ge
Angular JS and Node JS (21CSL581)
Course outcomes (Course Skill Set):
At the end of the course the student will be able to:
1. Develop Angular JS programs using basic features
2. Develop dynamic Web applications using AngularJS modules
3. Make use of form validations and controls for interactive applications
4. Appy the concepts of Expressions, data bindings and filters in developing Angular JS programs 5.
Make use of modern tools to develop Web applications

Assessment Details (both CIE and SEE)

The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks). A student shall be
deemed to have satisfied the academic requirements and earned the credits allotted to each course. The
student has to secure not less than 35% (18 Marks out of 50) in the semester-end examination (SEE). The
student has to secure a minimum of 40% (40 marks out of 100) in the sum
totaloftheCIE(ContinuousInternalEvaluation)andSEE (SemesterEndExamination)takentogether.

Continuous Internal Evaluation (CIE):

CIE marks for the practical course is 50 Marks.

The split-up of CIE marks for record/ journal and test are in the ratio 60:40.

• Each experiment to be evaluated for conduction with observation sheet and record write-up. Rubrics for
the evaluation of the journal/write-up for hardware/software experiments designed by the faculty who is
handling the laboratory session and is made known to students at the beginning of the practicalsession.
• Record should contain all the specified experiments in the syllabus and each experiment write-up will be
evaluated for 10marks.
• Total marks scored by the students are scaled downed to 30 marks (60% of maximummarks).
• Weightage to be given for neatness and submission of record/write-up ontime.
• Department shall conduct 02 tests for 100 marks, the first test shall be conducted after the 8 t^ week of
the semester and the second test shall be conducted after the 14'h week of thesemester.
• In each test, test write-up, conduction of experiment, acceptable result, and procedural knowledge will
carry a weightage of 60% and the rest 40% forviva-voce.
• The suitable rubrics can be designed to evaluate each student’s performance and learning ability. Rubrics
suggested in Annexure-II of Regulationbook
• The average of 02 tests is scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and average marks of two tests is the total
CIE marks scored by the student.

5|Pa ge
Angular JS and Node JS (21CSL581)
Lab Program #1 – Full Name
Objective
• Develop Angular program that allows user to input their first name and last name and display
their full name.
Note: The default values for first name and last name may be included in the program.

Steps
• Follow the commands 1-6, to create the Project skeleton.
• Verify the working of Angular application at http://localhost:4200/
• Update the below listed files in Files section, of the highlighted in Code section. Note: Non-
highlighted code is generated by the framework.
• Verify the functionality.
• Go through the Code explanation to understand it.

Files
File name Changes
app.module.ts Include FormsModule in import & NgModule-imports
app.component.ts Update the title for 'Program #1 - Full name'
app.component.html Include the title.
Include the submodules’ selectors.
program1-name.component.html Write a div block as per the view requirement.
program1-name.component.ts Write the code to supplement the corresponding view.

Code
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { Program1NameComponent } from './program1-name/program1-name.component';
import { FormsModule } from '@angular/forms';

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

// app.component.ts
import { Component } from '@angular/core';

@Component({

6|Pa ge
Angular JS and Node JS (21CSL581)
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: string = 'Lab Programs';
}

<!--app.component.html -->
<h1>{{title}}</h1>
<br>
<app-program1-name></app-program1-name>
<!-- program1-name.component.html -->
<div>
<h2>{{componentTitle}}</h2>
<br/>
<label>First Name:</label>
<input [(ngModel)]="firstName" (input)="updateFullName()" />
<label>Last Name:</label>
<input [(ngModel)]="lastName" (input)="updateFullName()" />
<br/><br/>
<p>Your Full Name: <b>{{ fullName }}</b></p>
</div>
// program1-name.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-program1-name',
templateUrl: './program1-name.component.html',
styleUrls: ['./program1-name.component.css']
})
export class Program1NameComponent {
firstName: string = 'Vijay';
lastName: string = 'Kumar';
fullName: string = '';
componentTitle: string = 'Program #1 - Full Name';

ngOnInit(): void {
this.updateFullName();
}
updateFullName(): void {
this.fullName = this.firstName +" "+ this.lastName;
}
}

7|Pa ge
Angular JS and Node JS (21CSL581)
Verification
URL http://localhost:4200/
Browser View

Explanation
• program1-name.component.html
o Input Fields: Two input fields are provided for the user to enter their first name and
last name. The [(ngModel)] directive enables two-way data binding, which means
that changes in the input fields will be reflected in the component class properties
(firstName and lastName), and vice versa.
o Event Binding: The (input) event is used on both input fields to trigger the
updateFullName() method whenever the user types or modifies the input. This
ensures that the full name is updated in real-time as the user types.
o Display Full Name: A paragraph (<p>) element displays the user's full name using
the {{ fullName }} expression. This expression binds to the fullName property in the
component class.
• program1-name.component.ts
o OnInit Lifecycle Hook: The component implements the OnInit interface, and the
ngOnInit lifecycle hook is used. This hook is called after Angular has initialized all
data-bound properties.
o Default Values: Default values for firstName and lastName are provided.
o updateFullName Method: The updateFullName method is defined to concatenate
the firstName and lastName properties and update the fullName property. This
method is called both in the ngOnInit lifecycle hook (to set the initial full name) and
in response to user input events.

8|Pa ge
Angular JS and Node JS (21CSL581)
Lab Program #2 – Shopping
Objective
• Develop an Angular application that displays a list of shopping items. Allow users to add and
remove items from the list using directives and component.
Note: The default values of items may be included in the program.

Steps
• Create new component for Program #2: named 'program2-shopping'.
=> ng g c program2-shopping
• Include the created component in Root component (ie, app.component.html).
=> <app-program2-shopping></app-program2-shopping>
• Update the code in files program2-shopping.component.ts and program2-
shopping.component.html as in below.

Files
File name Changes
app.component.html Include the submodule selector.
program2-shopping.component.html Write a div block as per the view requirement.
program2-shopping.component.ts Write the code to supplement the corresponding view.

Code
<!—program2-shopping.component.html -->
<div>
<h2>{{componentTitle}}</h2>
<br/>

<ul>
<li *ngFor="let item of items; let i = index">
{{ item }}
<button (click)="removeItem(i)">Remove</button>
</li>
</ul>

<div>
<input [(ngModel)]="newItem" placeholder="New Item" />
<button (click)="addItem(newItem)">Add</button>
</div>
</div>
// program2-shopping.component.ts
// Note: Insert the below code snippet inside the class

items: string[] = ['Angular Paperback','Node JS TextBook','Spring Boot Book'];


newItem: string = '';
componentTitle:string ="Shopping List";

addItem(item: string): void {


this.items.push(item);
this.newItem = '';

9|Pa ge
Angular JS and Node JS (21CSL581)
}

removeItem(index: number): void {


this.items.splice(index, 1);
}

Verification
URL http://localhost:4200/
Browser View

Explanation
• program2-shopping.component.html
o Shopping List Heading:
▪ The component contains an <h2> heading with the text "Program #2 -
Shopping List."
o List of Items:
▪ An unordered list (<ul>) is used to display the shopping items.
▪ The *ngFor directive is used to iterate over the items array in the component
class.
▪ For each item, a list item (<li>) is created, displaying the item's name.
▪ A "Remove" button is associated with each item, and the (click) event is
bound to the removeItem(i) method, passing the index i as an argument.
o Add Item Section:
▪ A <div> section is provided for adding new items.
▪ An input field with two-way data binding ([(ngModel)]="newItem") allows
the user to input the name of a new item.
▪ A "Add" button is associated with the addItem(newItem) method, triggering
the addition of the new item to the list.
• program2-shopping.component.ts
o Component Class:
▪ The Program2ShoppingComponent class is defined with the @Component
decorator.
▪ The selector property specifies the component's HTML selector, allowing it
to be used as <app-program2-shopping> in other templates.

o Properties:
▪ The items property is an array of strings representing the initial shopping list.
▪ The newItem property is a string used to store the name of a new item to be
added.

10 | P a g e
Angular JS and Node JS (21CSL581)
o addItem Method:
▪ The addItem method is triggered when the "Add" button is clicked.
▪ It takes an item (string) as a parameter, pushes it into the items array, and then
clears the newItem property.
▪ Note: items.push(item): This array function adds an ‘item’ element at end of
the array ‘items’.
o removeItem Method:
▪ The removeItem method is triggered when a "Remove" button is clicked.
▪ It takes an index as a parameter and uses the splice method to remove the
item at that index from the items array.
• This code implements a simple shopping list application where users can view a list of items,
add new items, and remove existing items. The use of two-way data binding with ngModel
ensures that changes in the input field are reflected in the component class, and vice versa.
The (click) events on the buttons trigger methods in the component class to update the list of
items accordingly.

11 | P a g e
Angular JS and Node JS (21CSL581)
Lab Program #3 – Calculator
Objective
• Develop a simple Angular calculator application that can perform basic mathematical
operations (addition, subtraction, multiplication, division) based on user input.

Steps
• Create new component for Program #3: named 'program3-calculator'.
=> ng g c program3-calculator
• Include the created component in Root component (ie, app.component.html).
=> <app-program3-calculator></app-program3-calculator>
• Update the code in files program3-calculator.component.ts and program3-
calculator.component.html as in below.

Files
File name Changes
app.component.html Include the submodule selector.
program3-calculator.component.html Write a div block as per the view requirement.
program3-calculator.component.ts Write the code to supplement the corresponding view.

Code
<!— program3-calculator.component.html -->
<h2>{{componentTitle}}</h2>
<br/>
<div>
<label for="num1">Number 1:</label>
<input type="number" [(ngModel)]="num1" id="num1" />
</div>
<div>
<label for="num2">Number 2:</label>
<input type="number" [(ngModel)]="num2" id="num2" />
</div>
<br/>
<div>
<button (click)="add()">Add</button>
<button (click)="subtract()">Subtract</button>
<button (click)="multiply()">Multiply</button>
<button (click)="divide()">Divide</button>
</div>

<div *ngIf="result !== undefined">


<p>Result: {{ result }}</p>
</div>
// program3-calculator.component.ts
// Note: Insert the below code snippet inside the class
public result: number = 0;
public num1: number = 0;
public num2: number = 0;
componentTitle:string ="Program #3 - Calculator";

12 | P a g e
Angular JS and Node JS (21CSL581)
add(): void {
this.result = this.num1 + this.num2;
}

subtract(): void {
this.result = this.num1 - this.num2;
}

multiply(): void {
this.result = this.num1 * this.num2;
}

divide(): void {
if (this.num2 !== 0) {
this.result = this.num1 / this.num2;
} else {
alert('Cannot divide by zero!');
}
}

Verification
URL http://localhost:4200/
Browser View

Explanation
• program3-calculator.component.html
o The template consists of two input fields for entering numbers (num1 and num2).
o Four buttons are provided for performing addition, subtraction, multiplication, and
division.
o The buttons are wired to call corresponding methods (add(), subtract(), multiply(),
and divide()) when clicked.
o The result of the operation is displayed below the buttons, but only if the result is
defined (*ngIf="result !== undefined").

• program3-calculator.component.ts
o The TypeScript component defines three public properties (result, num1, and num2)
to store the result and input numbers.
o The componentTitle property holds the title of the calculator.

13 | P a g e
Angular JS and Node JS (21CSL581)
o Four methods (add(), subtract(), multiply(), and divide()) perform the corresponding
mathematical operations and update the result property.
o The divide() method includes a check to avoid division by zero and displays an alert
if the user attempts to divide by zero.
• This Angular calculator allows users to input two numbers, perform basic operations, and see
the result on the page. The use of two-way data binding ([(ngModel)]) ensures that changes
in the input fields are reflected in the component properties and vice versa. The *ngIf
directive controls the visibility of the result section based on whether a result is available.

14 | P a g e
Angular JS and Node JS (21CSL581)
Lab Program #4 – Factorial & Square
Objective
• Write an Angular application that can calculate factorial and compute square based on given
user input.

Steps
• Create new component for Program #4: named 'program4-factorial'.
=> ng g c program4-factorial
• Include the created component in Root component (ie, app.component.html).
=> < app-program4-factorial></app-program4-factorial>
• Update the code in files program4-factorial.component.ts and program4-
factorial.component.html as in below.

Files
File name Changes
app.component.html Include the submodule selector.
program4-factorial.component.html Write a div block as per the view requirement.
program4-factorial.component.ts Write the code to supplement the corresponding view.

Code
<!— program4-factorial.component.html -->
<div>
<h2>{{componentTitle}}</h2>
<br/>
<label for="numberInput">Enter a number:</label>
<input type="number" id="numberInput" [(ngModel)]="inputNumber" />
</div>
<br/>
<div>
<button (click)="calculateFactorial()">Calculate Factorial</button>
&nbsp;&nbsp;<b>Factorial: {{ factorialResult }}</b>
</div>
<div>
<button (click)="calculateSquare()">Calculate Square</button>
&nbsp;&nbsp;<b>Square: {{ squareResult }}</b>
</div>
// program4-factorial.component.ts
// Note: Insert the below code snippet inside the class
inputNumber: number = 0;
factorialResult: number = 0;
squareResult: number = 0;
componentTitle: string = "Program #4 - Factorial and Square";

calculateFactorial() {
if (this.inputNumber >= 0) {
this.factorialResult = this.factorial(this.inputNumber);
} else {
this.factorialResult = 0; // Handle negative input

15 | P a g e
Angular JS and Node JS (21CSL581)
}
}

calculateSquare() {
this.squareResult = Math.pow(this.inputNumber, 2);
}

factorial(n: number): number {


if (n === 0 || n === 1) {
return 1;
} else {
return n * this.factorial(n - 1);
}
}

Verification
URL http://localhost:4200/
Browser View

Explanation
• program4-factorial.component.html
o The input field with [(ngModel)]="inputNumber" is two-way data-bound to the
inputNumber property in the component class. It allows the user to input a number.
o Two buttons trigger the calculateFactorial() and calculateSquare() methods when
clicked.
o The results of the calculations are displayed using Angular interpolation ({{}}),
showing the factorial and square results.
• program4-factorial.component.ts
o The TypeScript component class defines properties like inputNumber, factorialResult,
squareResult, and componentTitle.
o Methods like calculateFactorial(), calculateSquare(), and factorial(n: number) handle
the logic for calculating the factorial and square.
o calculateFactorial() checks if the input is non-negative before computing the
factorial. If the input is negative, it sets the result to 0.
o calculateSquare() uses the Math.pow() method to calculate the square of the input
number.
o The factorial(n: number) method is a recursive function to calculate the factorial of a
given number.

16 | P a g e
Angular JS and Node JS (21CSL581)
Lab Program #5 – Students List
Objective
• Develop Angular application that displays a details of students and their CGPA. Allow users to
read the number of students and display the count. Note: Student details may be included in
the program.

Steps
• Create new component for Program #5: named 'program5-students'.
=> ng g c program5-students
• Include the created component in Root component (ie, app.component.html).
=> < app- program5-students ></app- program5-students >
• Update the code in files program5-students.component.ts and program5-
students.component.html as in below.

Files
File name Changes
app.component.html Include the submodule selector.
program5-students.component.html Write a div block as per the view requirement.
program5-students.component.ts Write the code to supplement the corresponding view.

Code
<!— program5-students.component.html -->
<div>
<h2>{{componentTitle}}</h2>
<br/>
<label for="numberOfStudents">Enter the number of students:</label>
<input type="text" id="numberOfStudents" [(ngModel)]="numberOfStudents"
/>

<button (click)="generateStudentDetails()">Generate Student


Details</button>(Max count:15)

<div *ngIf="students.length > 0">


<p>Total Students: {{ students.length }}</p>

<table>
<thead>
<tr class="trCls">
<th>USN</th>
<th>Name</th>
<th>Contact number</th>
<th>CGPA</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of students">
<th>{{student.usn}}</th>
<th>{{student.name}}</th>

17 | P a g e
Angular JS and Node JS (21CSL581)
<th>{{student.contactNum}}</th>
<th>{{student.cgpa}}</th>
</tr>
</tbody>
</table>
</div>
</div>
// program5-students.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-program5-students',
templateUrl: './program5-students.component.html',
styleUrls: ['./program5-students.component.css'],
})
export class Program5StudentsComponent {
componentTitle: string = "Program #5 - Students Details";
numberOfStudents: number = 0;
students: Student[] = [];

generateStudentDetails() {
if(this.numberOfStudents>=0) {
this.students = this.loadStudents().slice(0,this.numberOfStudents);
}
}

loadStudents(): Student[] {
return [
{usn:"4SU21CS1E001",name:"Ram",contactNum:9512456718,cgpa:3},
{usn:"4SU21CSE002",name:"Vinay",contactNum:9512456721,cgpa:4},
{usn:"4SU21CSE003",name:"Krishna",contactNum:9512456722,cgpa:5},
{usn:"4SU21CSE004",name:"Prasad",contactNum:9512456723,cgpa:2},
{usn:"4SU21CSE005",name:"Geetha",contactNum:9512456724,cgpa:3},
{usn:"4SU21CSE006",name:"Seetha",contactNum:9512456725,cgpa:4},
{usn:"4SU21CSE007",name:"Amar",contactNum:9512456726,cgpa:5},
{usn:"4SU21CSE008",name:"Keerthi",contactNum:9512456727,cgpa:2},
{usn:"4SU21CSE009",name:"Prasad",contactNum:9512456728,cgpa:3},
{usn:"4SU21CSE010",name:"Vishnu",contactNum:9512456729,cgpa:2},
{usn:"4SU21CSE011",name:"Bahadhur",contactNum:9512456731,cgpa:5},
{usn:"4SU21CSE012",name:"Vani",contactNum:9512456732,cgpa:5},
{usn:"4SU21CSE013",name:"Krunal",contactNum:9512456733,cgpa:4},
{usn:"4SU21CSE014",name:"Sachin",contactNum:9512456734,cgpa:4},
{usn:"4SU21CSE015",name:"Vamshi",contactNum:9512456735,cgpa:3},
];
}
}

18 | P a g e
Angular JS and Node JS (21CSL581)
interface Student {
usn: string;
name: string;
contactNum: number;
cgpa: number;
}

Verification
URL http://localhost:4200/
Browser
View

Explanation
• program5-students.component.html
o The input field with [(ngModel)]="numberOfStudents" is two-way data-bound to the
numberOfStudents property in the component class, allowing users to input the
number of students.
o The button (click)="generateStudentDetails()" triggers the generateStudentDetails()
method when clicked. There's also a note indicating the maximum count of students
(15).
o Using *ngIf, it checks if there are students available before displaying the table.
• program5-students.component.ts
o The TypeScript component class defines properties like componentTitle,
numberOfStudents, and an array students to store student details.
o The generateStudentDetails() method is called when the button is clicked. It checks if
the entered number of students is non-negative and then generates the student
details accordingly.
o The loadStudents() method provides an array of sample student details, including
their USN, name, contact number, and CGPA.
• In summary, this Angular application allows users to input the number of students, and upon
clicking the button, it generates and displays the details of students, including their USN,
name, contact number, and CGPA, in a table format.

19 | P a g e
Angular JS and Node JS (21CSL581)
Lab Program #6 – To-Do list
Objective
• Develop an AngularJS program to create a simple to-do list application. Allow users to add,
edit, and delete tasks. Note: The default values for tasks may be included in the program.

Steps
• Create new component for Program #6: named 'program6-todo'.
=> ng g c program6-todo
• Include the created component in Root component (ie, app.component.html).
=> < app- program6-todo ></app- program6-todo >
• Update the code in files program6-todo.component.ts and program6-todo.component.html as
in below.

Files
File name Changes
app.component.html Include the submodule selector.
program6-todo.component.html Write a div block as per the view requirement.
Program6-todo.component.ts Write the code to supplement the corresponding view.

Code
<!— program6-todo.component.html -->
<div>
<h2>{{componentTitle}}</h2>
<br/>

<table>
<thead>
<tr class="trCls">
<td>Task</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let task of tasks" >
<td>{{ task.title }}</td>
<td><button (click)="editTask(task)">Edit</button>
<button (click)="deleteTask(task)">Delete</button>
</td>
</tr>
</tbody>
</table>

<div class="add-task">
<input [(ngModel)]="newTaskTitle" placeholder="New Task" />
<button (click)="addTask()">Add</button>
</div>
</div>

20 | P a g e
Angular JS and Node JS (21CSL581)
// program6-todo.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-program6-todo',
templateUrl: './program6-todo.component.html',
styleUrls: ['./program6-todo.component.css']
})
export class Program6TodoComponent {
componentTitle: string = "Program #6 - To-Do List";
tasks: Task[] = [
{ id: 1, title: 'Task 1'},
{ id: 2, title: 'Task 2' },
{ id: 3, title: 'Task 3' },
];

newTaskTitle: string = '';

addTask() {
if (this.newTaskTitle.trim() !== '') {
const newTask: Task = {
id: this.tasks.length + 1,
title: this.newTaskTitle
};

this.tasks.push(newTask);
this.newTaskTitle = '';
}
}

editTask(task: Task) {
const newTitle = prompt('Edit task:', task.title);

if (newTitle !== null) {


task.title = newTitle;
}
}

deleteTask(task: Task) {
const index = this.tasks.indexOf(task);
if (index !== -1) {
this.tasks.splice(index, 1);
}
}
}

interface Task {
id: number;

21 | P a g e
Angular JS and Node JS (21CSL581)
title: string;
}

Verification
URL http://localhost:4200/
Browser View

Explanation
• program6-todo.component.html
o The template defines a component with a title ({{componentTitle}}) and a table to
display tasks. It uses Angular's *ngFor directive to iterate over tasks and display them
in rows with "Edit" and "Delete" buttons.
o The "Add Task" section includes an input field bound to newTaskTitle using two-way
data binding ([(ngModel)]). The "Add" button triggers the addTask() method when
clicked.

• program6-todo.component.ts
o The TypeScript file defines an Angular component named Program6TodoComponent.
o It includes a title (componentTitle), an array of tasks (tasks), and an input field
(newTaskTitle).
o The component has methods (addTask, editTask, and deleteTask) to perform add, edit,
and delete operations on tasks.
o An interface Task is defined for the structure of a task object.
• The application provides a basic structure for a to-do list with Angular, including
functionalities for adding, editing, and deleting tasks. Users can interact with the UI to
manage their to-do list.

22 | P a g e
Angular JS and Node JS (21CSL581)
Appendix
Commands
Command/Caption Env Note
1 cd <your_workspace_path> CMD Specific Batch name directory
ng new lab_programs New webapp creations: lab_programs in this case
2 Note: Routing - n
choose 'CSS' CMD
3 cd lab_programs
Note: Privacy policy – n CMD
4 ng serve: Builds and Runs the application.
ng serve –open CMD --open: opens the browser whenbuild is done.
5 code . CMD Open the appln in VS Code

6 ng generate component <component_name>


For Program1: ng generate component Generate(g) new Component(c).
program1_name CMD Note: Named 'program1_name' in this case.
7 App URL Browser http://localhost:4200/
8 ctrl+c CMD Kill Process

Softwares and Installation


1) Install Node JS from (LTS version):
https://nodejs.org/
2) Install Visual Studio Code from:
https://code.visualstudio.com/
3) Install Angular (at CLI/Terminal)
npm install -g @angular/cli@16.2

23 | P a g e
Angular JS and Node JS (21CSL581)

You might also like