Angular JS Course: Application Setup Guide
Angular JS Course: Application Setup Guide
[Link]
Click on the Login button at the top right corner and observe the URL.
2. Login with different credentials (other than admin, admin) and see the message displayed.
3. Login with credentials (admin, admin) and check how the redirection is happening by observing the
URL.
4. Click on the two tabs (Tablets, Mobiles) which display tablet and mobile devices, respectively.
5. Click on any product name and see the product detail page getting displayed.
6. Click on Add to Cart button and add multiple products to the cart (selection count and the total price will be
displayed on the second navigation bar).
7. Click on the cart link on the second navigation bar and observe the cart page which displays the selected
products.
8. Click on the Checkout button and observe the page displayed. Click the Back button and observe the
navigation.
9. Click on the sort dropdown and observe sort functionality based on the options mentioned.
10. Click on the filter dropdown and observe filtering functionality based on the options mentioned.
11. In the search text box placed on the second navigation bar, type the manufacturer name like Samsung,
Apple, etc., and observe the search functionality.
12. Click on the Logout button at the top right corner and observe the redirection happening.
1
YJRDMS COLLEGE OF ENGINEERING
1. InCourse
1.b Name:
the same MyAppAngular JS
application created earlier, create a new component called hello using the
following
Module Name:CLI command
Components and Modules
Create a newng
D:\MyApp> component
generate called hello and
component render Hello Angular on the page
hello
2. This command will create a new folder with the name hello with the following files placed
inside it
3. 3. Open [Link] file and create a property called courseName of type string and
initialize it to "Angular" as shown below
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './[Link]', styleUrls:
['./[Link]']})
export class HelloComponent implements OnInit { courseName: string =
"Angular";
constructor() { }
ngOnInit() {
}
}
12. <title>MyApp</title>
13. <base href="/">
14. <meta name="viewport" content="width=device-width, initial-scale=1">
15. <link rel="icon" type="image/x-icon" href="[Link]">
16. </head>
17. <body>
18. <app-hello></app-hello>
19. </body>
20. </html>
8. Now run the application by giving the following command D:\
MyApp>ng serve –open
Output:
3
YJRDMS COLLEGE OF ENGINEERING
1. Open [Link], add a method called changeName() as shown below in Line 12-14. Also, use
external template [Link].
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: "./[Link]",
styleUrls: ['./[Link]']
})
export class HelloComponent implements OnInit
{ courseName = "Angular";
constructor() { }
ngOnInit() {
}
changeName() {
[Link] = "TypeScript";
}
}
2. Open [Link] and add a paragraph and bind it with changeName() method as shown in
Line 3
<h1>Welcome</h1>
<h2>Course Name: {{ courseName }}</h2>
<p (click)="changeName()">Click here to change</p>
3. Save the files and check the output in the browser.
Output:
4
YJRDMS COLLEGE OF ENGINEERING
Problem Statement:
You will be progressively building the PoolCarz application throughout this course.
PoolCarz is a web application for carpooling. The application allows users to share rides with others. Users can
either book a ride or offer a ride.
Use Cases:
Login Book a
ride Ride
details Offer
Ride Logout
1. Login: Login to the application to view ride details
2. Book a ride: Renders the rides available and also allows to filter the details based on the start/endpoint of
the rides.
5
YJRDMS COLLEGE OF ENGINEERING
3. Ride Details: When a user selects a particular ride, it renders complete details about that ride and allows
the user to book that ride.
gister their
details to offer a ride to others.
6
YJRDMS COLLEGE OF ENGINEERING
7
YJRDMS COLLEGE OF ENGINEERING
3. Add AppComponent to the bootstrap property in the root module file i.e., [Link]
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './[Link]';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
4. Ensure the [Link] displays app-root.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
<body>
<app-root></app-root>
</body>
</html>
5. Save the files and check the output in the browser.
Output:
8
YJRDMS COLLEGE OF ENGINEERING
Output:
9
YJRDMS COLLEGE OF ENGINEERING
Output:
10
YJRDMS COLLEGE OF ENGINEERING
It also adds repeat directive to the root module i.e., [Link] to make it available to the entire
module as shown below in Line 7
...
import { RepeatDirective } from './[Link]';
@NgModule({
declarations: [
AppComponent,
RepeatDirective
],
...
})
export class AppModule { }
11
YJRDMS COLLEGE OF ENGINEERING
[Link]
<h3>Structural Directive</h3>
<p *appRepeat="5">I am being repeated...</p>
Output:
12
YJRDMS COLLEGE OF ENGINEERING
Output:
13
YJRDMS COLLEGE OF ENGINEERING
Outpu
14
YJRDMS COLLEGE OF ENGINEERING
It also adds message directive to the root module i.e., [Link] to make it available
to the entire module as shown below
...
import { MessageDirective } from './[Link]';
@NgModule({
declarations: [
AppComponent,
MessageDirective
],
...
})
export class AppModule { }
[Link]
[Link]
<h3>Attribute Directive</h3>
<p [appMessage]="myMessage">Click Here</p>
Output:
16
YJRDMS COLLEGE OF ENGINEERING
Output:
17
YJRDMS COLLEGE OF ENGINEERING
18
YJRDMS COLLEGE OF ENGINEERING
}
2. Write the below-given code in [Link]
<input type="text" [(ngModel)]="name"> <br/>
<div>Hello , {{ name }}</div>
3. Write the below-given code in [Link]
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from
'@angular/core';
import { FormsModule } from '@angular/forms'; import { AppComponent }
from './[Link]'; @NgModule({
declarations: [ AppComponent
],
imports: [ BrowserModule, FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
4. Save the files and check the output in the browser
19
YJRDMS COLLEGE OF ENGINEERING
Output:
20
YJRDMS COLLEGE OF ENGINEERING
</table>
3. Write the below-given code in [Link]
import { BrowserModule } from '@angular/platform-browser'; import {
NgModule } from '@angular/core';
import { AppComponent } from './[Link]';
Output:
22
YJRDMS COLLEGE OF ENGINEERING
The above command will create a folder with name courses-list with the following files
[Link]
[Link]
[Link]
[Link]
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let course of courses">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
</tbody>
</table>
5. Add the following code in [Link]
tr{
text-align:cente;}
</div>
7. Write the below-given code in [Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent { show!:
boolean;
}
8. Save the files and check the output in the browser
Output:
24
YJRDMS COLLEGE OF ENGINEERING
1. Open the [Link] file created in the example of nested components and
add the following code
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-courses-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class CoursesListComponent
{ courses = [
{ courseId: 1, courseName: 'Node JS' },
{ courseId: 2, courseName: 'Typescript' },
{ courseId: 3, courseName: 'Angular' },
{ courseId: 4, courseName: 'React JS' },
];
course!: any[];
@Input() set cName(name: string) {
[Link] = [];
for (var i = 0; i < [Link]; i++) { if
([Link][i].courseName === name) {
[Link]([Link][i]);
}
}
}
}
2. Open [Link] and add the following code
<table border="1" *ngIf="[Link] > 0">
<thead>
<tr>
<th>Course ID</th>
<th>Course Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let c of course">
<td>{{ [Link] }}</td>
<td>{{ [Link] }}</td>
</tr>
25
YJRDMS COLLEGE OF ENGINEERING
</tbody>
</table>
3. Add the following in [Link]
<h2>Course Details</h2>
Select a course to view
<select #course (change)="name = [Link]">
<option value="Node JS">Node JS</option>
<option value="Typescript">Typescript</option>
<option value="Angular">Angular</option>
<option value="React JS">React JS</option></select><br /><br />
<app-courses-list [cName]="name"></app-courses-list>
4. Add the following in [Link] import
{ Component } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./[Link]'],
templateUrl: './[Link]'
})
export class AppComponent
{ name!: string;
}
Output:
26
YJRDMS COLLEGE OF ENGINEERING
[Link]
...
export class CoursesListComponent {
@Output() onRegister = new EventEmitter<string>();
...
register(courseName: string) {
[Link](courseName);
}
}
[Link]
<table border="1">
...
<tbody>
<tr *ngFor="let course of courses">
<td>{{[Link]}}</td>
<td>{{[Link]}}</td>
<td><button (click)="register([Link])">Register</button></td>
</tr>
</tbody>
</table>
[Link]
<h2> Courses List </h2>
<app-courses-list (OnRegister)="courseReg($event)"></app-courses-list>
<br/><br/>
<div *ngIf="message">{{message}}</div>
[Link]
...
export class AppComponent {
27
YJRDMS COLLEGE OF ENGINEERING
28
YJRDMS COLLEGE OF ENGINEERING
Output:
29
YJRDMS COLLEGE OF ENGINEERING
[Link]
import {
Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./[Link]'],
templateUrl: './[Link]'
})
export class AppComponent implements OnInit, DoCheck,
AfterContentInit, AfterContentChecked,
AfterViewInit, AfterViewChecked,
OnDestroy {
data = 'Angular';
ngOnInit() {
[Link]('Init');
}
ngDoCheck(): void { [Link]('Change
detected');
}
ngAfterContentInit(): void
{ [Link]('After content init');
}
ngAfterContentChecked(): void
{ [Link]('After content checked');
}
ngAfterViewInit(): void
{ [Link]('After view init');
}
ngAfterViewChecked(): void
{ [Link]('After view checked');
}
ngOnDestroy(): void {
[Link]('Destroy');
}
}
[Link]
30
YJRDMS COLLEGE OF ENGINEERING
<div>
<h1>I'm a container component</h1>
<input type="text" [(ngModel)]='data'>
<app-child [title]='data'></app-child>
</div>
[Link]
...
export class ChildComponent implements OnChanges { @Input()
title: string = 'I\'m a nested component'; ngOnChanges(changes:
any): void {
[Link]('changes in child:' + [Link](changes));
}
}
Output:
31
YJRDMS COLLEGE OF ENGINEERING
</div>
<div class="form-group">
<fieldset formGroupName="address">
<label>Street</label>
<input type="text" class="form-control" formControlName="street" />
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip" />
<label>City</label>
<input type="text" class="form-control" formControlName="city" />
</fieldset>
</div>
<button type="submit" class="btn btn-primary" (click)="submitted = true">
Submit
</button>
</form>
<br/>
<div [hidden]="!submitted">
<h3>Employee Details</h3>
<p>First Name: {{ [Link] }}</p>
<p>Last Name: {{ [Link] }}</p>
<p>Street: {{ [Link] }}</p>
<p>Zip: {{ [Link] }}</p>
<p>City: {{ [Link] }}</p>
</div>
</div>
Output:
33
YJRDMS COLLEGE OF ENGINEERING
<div class="container">
<h1>Registration Form</h1>
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName">
<div *ngIf="[Link]['firstName'].errors" class="alert alert-danger">
Firstname field is invalid.
<p *ngIf="[Link]['firstName'].errors?.['required']"> This
field is required!
</p>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName">
<div *ngIf="[Link]['lastName'].errors" class="alert alert-danger"> Lastname
field is invalid.
<p *ngIf="[Link]['lastName'].errors?.['required']"> This
field is required!
</p>
</div>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<legend>Address:</legend>
<label>Street</label>
<input type="text" class="form-control" formControlName="street">
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip">
<label>City</label>
<input type="text" class="form-control" formControlName="city">
</fieldset>
</div>
<button type="submit" class="btn btn-primary" (click)="submitted=true">Submit</button>
35
YJRDMS COLLEGE OF ENGINEERING
</form>
<br/>
<div [hidden]="!submitted">
<h3> Employee Details </h3>
<p>First Name: {{ [Link]('firstName')?.value }} </p>
.ng-valid[required] {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid:not(form) {
border-left: 5px solid #a94442; /* red */
}
<app-registration-form></app-registration-form>
Output:
36
YJRDMS COLLEGE OF ENGINEERING
2. Add HTML controls for the email field in the [Link] file as shown below
<div class="container">
<h1>Registration Form</h1>
37
YJRDMS COLLEGE OF ENGINEERING
<form [formGroup]="registerForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName" />
<p *ngIf="[Link]?.required"> This field is required!
</p>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" formControlName="lastName" />
<div *ngIf="[Link]" class="alert alert-danger">
Lastname field is invaliddd.
<p *ngIf="[Link]?.required">
This field is required!
</p>
</div>
</div>
<div class="form-group">
<fieldset formGroupName="address">
<label>Street</label>
<input type="text" class="form-control" formControlName="street" />
<label>Zip</label>
<input type="text" class="form-control" formControlName="zip" />
<label>City</label>
<input type="text" class="form-control" formControlName="city" />
</fieldset>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" formControlName="email" />
<div *ngIf="[Link]" class="alert alert-danger"> Email
field is invalid.
<p *ngIf="[Link]?.required">
This field is required!
</p>
<p *ngIf="[Link]?.emailInvalid">
{{ [Link]?.[Link] }}
</p>
</div>
</div>
<button type="submit" class="btn btn-primary" (click)="submitted = true">
Submit
</button>
</form>
38
YJRDMS COLLEGE OF ENGINEERING
<br/>
<div [hidden]="!submitted">
<h3>Employee Details</h3>
<p>First Name: {{ [Link] }}</p>
<p>Last Name: {{ [Link] }}</p>
<p>Street: {{ [Link] }}</p>
<p>Zip: {{ [Link] }}</p>
Output:
39
YJRDMS COLLEGE OF ENGINEERING
The code inside [Link] is present under the login folder. Observe the creation of
LoginComponent as a reactive form and addition of validations to it.
again...</div>
<div *ngIf="!valid" class="error">Invalid Credentials...Please try
<br />
<div class="form-group">
<span class="col-xs-4"></span>
<div class="col-xs-3">
<button (click)="onSubmit()" class="btn btn-primary"
[disabled]="![Link]">Login</button>
</div>
<span class="col-xs-5" style="top:8px">
<a [routerLink]="['/welcome']"
style="color:#337ab7;text-decoration: underline;">Cancel</a>
</span>
</div>
</form>
41
YJRDMS COLLEGE OF ENGINEERING
Observe the creation of model-driven form within the LoginComponent. Open [Link]. import {
//fetches the form object containing the values of all the form controls
[Link] = [Link]();
const user = [Link](currUser => [Link] === [Link] &&
[Link] === [Link])[0];
if (user) {
[Link] = [Link];
[Link](['/products']);
} else {
[Link] = false;
}
}
}
42
YJRDMS COLLEGE OF ENGINEERING
Outpu
43
YJRDMS COLLEGE OF ENGINEERING
4. Create a service called BookService under the book folder using the following CLI command
8. Create a service called BookService under the book folder using the following CLI command
return BOOKS;
}
}
[Link]();
}
}
12. Add the following code in [Link] which has styles for books
.books {
margin: 0 0 2em 0; list-
style-type: none;
padding: 0;
width: 13em;
}
.books li { cursor:
pointer;
position: relative; left:
46
YJRDMS COLLEGE OF ENGINEERING
0;
background-color: #eee;
margin: 0.5em; padding:
0.3em 0; height: 1.5em;
border-radius: 4px;
}
.books li:hover
{ color: #607d8b;
background-color: #ddd;
left: 0.1em;
}
.books .badge { display:
inline-block; font-size:
small; color: white;
padding: 0.8em 0.7em 0 0.7em;
background-color: #607d8b; line-
height: 0.5em;
position: relative; left:
-1px;
top: -4px; height:
1.8em;
margin-right: 0.8em; border-
radius: 4px 0 0 4px;
}
<app-book></app-book>
Output:
47
YJRDMS COLLEGE OF ENGINEERING
[Link]
Output:
48
YJRDMS COLLEGE OF ENGINEERING
In the example used for custom services concept, add HttpModule to the [Link] to make use of
HttpClient class.
catchError([Link]))
options }).pipe(
})
export class AppModule { }
Add the following code in [Link] file
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from
'@angular/common/http';
import { Observable, throwError } from 'rxjs'; import
{ catchError, tap } from 'rxjs/operators'; import
{ Book } from './book';
@Injectable({ providedIn:'root'
})
export class BookService {
booksUrl = '[Link]
constructor(private http: HttpClient) { } getBooks():
Observable<Book[]> {
return [Link]<Book[]>('[Link] tap((data:
any) => [Link]('Data Fetched:' + [Link](data))),
catchError([Link]));
}).pipe(
}
updateBook(book: Book): Observable<any> {
const options = new HttpHeaders({ 'Content-Type': 'application/json' }); return
49
YJRDMS COLLEGE OF ENGINEERING
[Link]({id, name })
.subscribe({next:(book: any) => [Link](book)});
}
updateBook(bookId: string, name: string): void { let
id=parseInt(bookId)
[Link]({ id, name })
.subscribe({next:(book: any) => [Link] = book});
}
deleteBook(bookId: string): void { let
id=parseInt(bookId)
[Link](id)
.subscribe({next:(book: any) => [Link] = book});
}
ngOnInit() { [Link]();
}
}
Output:
51
YJRDMS COLLEGE OF ENGINEERING
[Link]
[
{
"productId": 1,
"productName": "Samsung Galaxy Note 7", "productCode":
"MOB-120",
"description": "64GB, Coral Blue",
"price": 800,
}
{}]
"imageUrl": "assets/imgs/samsung_note7_coralblue.jpg", "manufacturer":
"Samsung",
"ostype": "Android", "rating": 4
"productId": 2,
"productName": "Samsung Galaxy Note 7", "productCode": "MOB-124",
"description": "64GB, Gold", "price": 850,
"imageUrl": "assets/imgs/samsung_note7_gold.jpg", "manufacturer":
"Samsung",
"ostype": "Android", "rating": 4
[Link]
[
{
"productId": 1,
"productName": "Apple iPad Mini 2", "productCode":
"TAB-120", "description": "16GB, White", "price": 450,
"imageUrl": "assets/imgs/apple_ipad_mini.jpg", "manufacturer":
"Apple",
"ostype": "iOS", "rating": 4
"productId": 2,
"productName": "Apple iPad Air2", "productCode":
"TAB-124", "description": "64GB, Black", "price":
600,
"imageUrl": "assets/imgs/ipad_air.jpg", "manufacturer":
52
YJRDMS COLLEGE OF ENGINEERING
"Apple",
53
YJRDMS COLLEGE OF ENGINEERING
{}]
Explore the methods present in the [Link] file from the products folder. Observe the
code given below:
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators'
import { Product } from './product';
@Injectable()
export class ProductService
{ selectedProducts: any = [];
products: any = [];
producttype="tablet";
username: string = '';
// Fetches selectedProducts data from the sessionStorage
constructor(private http: HttpClient) {
if ([Link]('selectedProducts')) {
[Link] = [Link]([Link]('selectedProducts') + '');
}
}
// Makes a get request to backend to fetch products data
getProducts(): Observable<Product[]> {
if ([Link] === 'tablet') {
return [Link]<Product[]>('./assets/products/[Link]').pipe(
tap((products) => [Link] = products),
catchError([Link]));
} else if ([Link] === 'mobile') {
return [Link]<Product[]>('./assets/products/[Link]').pipe(
tap((products) => [Link] = products),
catchError([Link]));
}
else
throw new Error();
}
// Fetches the selected product details getProduct(id:
number): Observable<Product> {
return [Link]().pipe(
map(products => [Link](product => [Link] === id)[0]));
}
// Error Handling code
private handleError(err: HttpErrorResponse) {
return throwError(() => [Link]() || 'Server error');
}
}
54
YJRDMS COLLEGE OF ENGINEERING
55
YJRDMS COLLEGE OF ENGINEERING
56
YJRDMS COLLEGE OF ENGINEERING
ngOnInit() { [Link]++;
[Link]()
.subscribe({ next:products
=> {
[Link] = products;
[Link] = [Link];
[Link] =[Link]
},
error:error => [Link] = error});
if ([Link] > 0) {
[Link] = Number([Link]('selectedItems'));
[Link] = Number([Link]('grandTotal'));
}
}
checkManufacturers(cManuf: any[], cProducts: any[], chkman: any[]) { if
([Link] > 0) {
for (let checkManuf of cManuf) { for
(let checkProd of cProducts) {
if ([Link]() === [Link]()) {
[Link](checkProd);
}
}
}
} else {
[Link] = cProducts;
}
}
checkOpsystem(cOS: any[], chkman: any[], chkmanos: any[]) { if
([Link] > 0) {
for (let checkOS of cOS) {
for (let chkmann of chkman) {
if ([Link]() === [Link]()) { [Link](chkmann);
}
}
}
} else {
[Link] = chkman;
}
}
checkPrices(checkedPrice: any[], chkmanosprice: any[], chkmanos: any[]) { if
([Link] > 0) {
for (let checkPrice of checkedPrice) { for
(let chkmanfos of chkmanos) {
if (checkPrice === '300-450') {
57
YJRDMS COLLEGE OF ENGINEERING
}
}
// filtering functionality
filter(name: any) {
let checkedProducts: any[];
[Link] = []; [Link]
= []; [Link] = [];
const index = 0;
checkedProducts = [Link];
58
YJRDMS COLLEGE OF ENGINEERING
[Link] = [Link];
}
// Invoked when user clicks on Add to Cart button
// Adds selected product details to service class variable
// called selectedProducts
addCart(id: number) {
[Link] = new Cart();
[Link] += 1;
// fetching selected product details
const product = [Link]((currProduct: any) => [Link]
=== id)[0];
[Link] += [Link]; [Link]('selectedItems',
[Link]);
const sp = [Link]((currProduct: any) =>
[Link] === id)[0];
if (sp) {
const index = [Link]((currProduct: any) =>
[Link] === id);
[Link][index].quantity += 1;
[Link][index].totalPrice += [Link];
} else {
[Link] = 'ORD_' + [Link];
[Link] = id;
[Link] = [Link]('username') + '';
[Link] = [Link]; [Link] =
[Link];
[Link] = 1;
[Link] = new Date().toString(); [Link] =
[Link] * [Link];
[Link]([Link]);
[Link]('selectedProducts',
[Link]([Link]));
[Link]++;
}
}
// Search box functionality
// Searches based on manufacturer name searchtext()
{
[Link] = [Link]; if
([Link] > 0) {
[Link] = [Link]((product: Product) =>
[Link]().indexOf([Link]) !== -1);
}
}
// Invoked when a tab (Tablets/Mobiles) is clicked
59
YJRDMS COLLEGE OF ENGINEERING
}
// Invoked when user select an option in sort drop down
// changes the sortoption value accordingly
onChange(value: string) {
[Link] = value;
}
}
Output:
60
YJRDMS COLLEGE OF ENGINEERING
61
YJRDMS COLLEGE OF ENGINEERING
-moz-box-sizing: border-box;
box-sizing: border-box;
}
h3 {
text-align: center;
margin-bottom: 0;
}
[class*="col-"] { padding-
right: 20px; padding-
bottom: 20px;
}
[class*="col-"]:last-of-type
{ padding-right: 0;
}
.grid { margin:
0;
}
.col-1-4 { width:
25%;
}
.module { padding:
20px; text-align:
center; color: #eee;
max-height: 120px;
min-width: 120px;
background-color: #607d8b;
border-radius: 2px;
}
h4 {
position: relative;
}
.module:hover { background-
color: #eee; cursor: pointer;
color: #607d8b;
}
.grid-pad { padding:
10px 0;
}
.grid-pad > [class*="col-"]:last-of-type
{ padding-right: 20px;
}
@media (max-width: 600px) {
.module {
font-size: 10px;
62
YJRDMS COLLEGE OF ENGINEERING
max-height: 75px;
}
}
@media (max-width: 1024px) {
.grid { margin:
0;
}
.module {
min-width: 60px;
}
}
6. Create another component called book-detail using the following command D:\
MyApp>ng generate component bookDetail
7. Open [Link] and add getTopBooks() method as shown below to fetch s
pecific book details
63
YJRDMS COLLEGE OF ENGINEERING
[Link]( param
s=>{
let n = [Link]("id");
[Link]=Number(n);
[Link]=[Link](m=>[Link]==[Link])
}
)
}
goBack() {
[Link]();
}
}
64
YJRDMS COLLEGE OF ENGINEERING
input { height:
2em;
font-size: 1em; padding-
left: 0.4em;
}
button {
margin-top: 20px;
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer; cursor:
hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled
{ background-color: #eee;
color: #ccc;
cursor: auto;
}
11. Generate PageNotFound component using the following CLI command D:\
MyApp>ng g c PageNotFound
12. Add below code to [Link]:
<div>
<h1>404 Error</h1>
<h1>Page Not Found</h1>
</div>
13. Add the below code to [Link]:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './book/[Link]';
import { DashboardComponent } from './dashboard/[Link]'; import
{ BookDetailComponent } from './book-detail/[Link]';
import { PageNotFoundComponent } from './page-not-found/[Link]'; const
appRoutes: Routes = [
{ path: 'dashboard', component: DashboardComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' },
{ path: 'books', component: BookComponent },
{ path: 'detail/:id', component: BookDetailComponent },
{ path: '**', component: PageNotFoundComponent },
];
@NgModule({ imports: [
65
YJRDMS COLLEGE OF ENGINEERING
[Link](appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
66
YJRDMS COLLEGE OF ENGINEERING
/* Master Styles */ h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif; font-
size: 250%;
}
h2, h3 { color:
#444;
font-family: Arial, Helvetica, sans-serif; font-
weight: lighter;
}
body { margin:
2em;
}
body, input[text], button { color:
#888;
font-family: Cambria, Georgia;
}
a{
cursor: pointer; cursor:
hand;
}
button {
font-family: Arial; background-
color: #eee; border: none;
padding: 5px 10px; border-
radius: 4px; cursor:
pointer; cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled
{ background-color: #eee;
color: #aaa;
cursor: auto;
}
/* Navigation link styles */ nav a {
padding: 5px 10px; text-
decoration: none; margin-
right: 10px; margin-top:
10px; display: inline-
block;
67
YJRDMS COLLEGE OF ENGINEERING
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link
{ color: #607D8B;
}
nav a:hover { color:
#039be5;
background-color: #CFD8DC;
}
nav [Link] { color:
#039be5;
}
/* everywhere else */
*{
font-family: Arial, Helvetica, sans-serif;
}
18. Open [Link] under the src folder and add the following code
/* You can add global styles to this file, and also import other style files */ body{
padding:10px;
}
19. Open [Link] file in book folder and add the following code
import { Component, OnInit } from '@angular/core';
import { BooksdataService } from './[Link]';
@Component({
selector: 'app-book',
templateUrl: './[Link]', styleUrls:
['./[Link]']
})
export class BookComponent implements OnInit {
68
YJRDMS COLLEGE OF ENGINEERING
Output:
69
YJRDMS COLLEGE OF ENGINEERING
70
YJRDMS COLLEGE OF ENGINEERING
username: [],
password: [],
});
}
onFormSubmit(): void {
const uname = [Link]; const
pwd = [Link];
[Link]
.isUserAuthenticated(uname, pwd)
.subscribe({next:(authenticated) => { if
(authenticated) {
[Link](['/books']);
} else {
[Link] = 'Invalid Credentials. Try again.';
}
}});
}
}
Add the following code to the [Link] file inside Login folder export
class User {
constructor(public userId: number, public username: string, public password: string) { }
}
Add the following code to the [Link] file present inside login folder.
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { User } from './user';
const USERS = [
new User(1, 'user1', 'user1'),
new User(2, 'user2', 'user2')
];
const usersObservable = of(USERS);
@Injectable({
providedIn: 'root'
})
export class LoginService { private
isloggedIn = false;
getAllUsers(): Observable<User[]> { return
usersObservable;
}
isUserAuthenticated(username: string, password: string): Observable<boolean> { return
[Link]().pipe(
map(users => {
const Authenticateduser = [Link](user => ([Link] === username) &&
([Link] === password));
71
YJRDMS COLLEGE OF ENGINEERING
if (Authenticateduser)
{ [Link] = true;
} else {
[Link] = false;
}
return [Link];
})
);
}
isUserLoggedIn(): boolean
{ return [Link];
}
}
Create another service class called [Link] inside login folder and add the
following code:
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router'; import
{ LoginService } from './[Link]'; @Injectable({
providedIn: 'root'
})
export class LoginGuardService implements CanActivate { constructor(private
loginService: LoginService, private router: Router) { } canActivate(): boolean {
if ([Link]()) { return
true;
}
[Link](['/login']);
return false;
}
}
Add the following code in [Link]
...
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{path: 'login',component:LoginComponent},
{ path: 'books', component: BookComponent, canActivate:[LoginGuardService] },
{ path: 'dashboard', component: DashboardComponent},
{ path: 'detail/:id', component: BookDetailComponent},
{ path: '**', component: PageNotFoundComponent },
];
...
72
YJRDMS COLLEGE OF ENGINEERING
Output:
73
YJRDMS COLLEGE OF ENGINEERING
2. Write the code given below in the [Link] file inside book folder.
import { authGuard } from './../login/[Link]';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookComponent } from './[Link]'; const
bookRoutes: Routes = [
{
path: '',
component: BookComponent,
canActivate: [authGuard]
}
];
@NgModule({
imports: [[Link](bookRoutes)],
exports: [RouterModule]
})
export class BookRoutingModule { }
3. Create the [Link] file inside book folder and add the following code
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BookComponent } from './[Link]';
import { BookRoutingModule } from './[Link]';
@NgModule({
imports: [CommonModule, BookRoutingModule], declarations:
[BookComponent]
})
export class BookModule { }
4. Add the following code to the [Link] file
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { BookDetailComponent } from './book-detail/[Link]';
import { DashboardComponent } from './dashboard/[Link]'; import
{ LoginComponent } from './login/[Link]';
import { PageNotFoundComponent } from './page-not-found/page-not-
[Link]';
const appRoutes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
74
YJRDMS COLLEGE OF ENGINEERING
75
YJRDMS COLLEGE OF ENGINEERING
Output:
76
YJRDMS COLLEGE OF ENGINEERING
77
YJRDMS COLLEGE OF ENGINEERING
78
YJRDMS COLLEGE OF ENGINEERING
79
YJRDMS COLLEGE OF ENGINEERING
80
YJRDMS COLLEGE OF ENGINEERING
errorMessage!: string;
constructor(private bookService: BookService, private router: Router) { }
getBooks() {
[Link]().subscribe({
next: books => {[Link](books);[Link] = books},
error:error => [Link] = <any>error
})
}
gotoDetail(book: Book): void
{ [Link](['/books/detail/', [Link]]);
}
ngOnInit(): void {
[Link]();
}
}
9. Update [Link] as below:
<div *ngIf="book">
<h2>{{ [Link] }} details!</h2>
<div><label>id: </label>{{ [Link] }}</div>
<div>
<label>name: </label> <input [(ngModel)]="[Link]" placeholder="name" />
</div>
<button (click)="goBack()">Back</button>
</div>
[Link] [Link] as below:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Book } from '../book/book';
import { BooksdataService } from '../book/[Link]';
@Component({
selector: 'app-book-detail',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class BookDetailComponent implements OnInit {
constructor(private route:ActivatedRoute, private bdetails:BooksdataService, private r:Router)
{}
bookid:any; book:any;
ngOnInit(): void {
[Link]( params=
>{
let n = [Link]("id"); [Link]=Number(n);
[Link]=[Link](m=>[Link]==[Link])
81
YJRDMS COLLEGE OF ENGINEERING
}
)
}
goBack() {
[Link](['/books'])
}
}
Output:
82
YJRDMS COLLEGE OF ENGINEERING
MONGODB
11. Course Name: MongoDB Essentials - A Complete MongoDB Guide
a Module Name: Installing MongoDB on the local computer, Create MongoDB Atlas
Cluster
Install MongoDB and configure ATLAS
Step 2: Now select the Shared option and click on Create for free usage.
83
YJRDMS COLLEGE OF ENGINEERING
Step 3: Now select cloud provider AWS or Google cloud for free hosting and then select the region
in which it should be hosted. And in the Cluster tier select M0 Sandbox for the free environment.
And If you want you can rename the cluster. It will take 4-5 minutes to set up the environment.
Step 4: Create a username and password then select database access to atlasAdmin and network
access to allow access to anywhere. That will be the username and password through which the user
can access the database given to who do you give access.
84
YJRDMS COLLEGE OF ENGINEERING
Step 5: Select Connect and then select connect with the MongoDB Shell then go to I have
MongoDB shell installed. Select the node version from there. And after that run the command in the
command line which is given. Then enter the password which the user has set earlier with the
username and password.
Step 6: Go to Connect then Connect your application select your node version. Now copy the
link given and paste it into your application where you connect MongoDB. And replace
<password> with your password.
And that’s it. Now you are connected with the MongoDB atlas.
85
YJRDMS COLLEGE OF ENGINEERING
Now that we've defined MongoDB CRUD operations, we can take a look at how to carry out the
individual operations and manipulate documents in a MongoDB database. Let's go into the processes
of creating, reading, updating, and deleting documents, looking at each operation in turn.
Create operation
For MongoDB CRUD, if the specified collection doesn't exist, the create operation will create the
collection when it's executed. Create operations in MongoDB target a single collection, not multiple
collections. Insert operations in MongoDB are atomic on a single document level.
MongoDB provides two different create operations that you can use to insert documents into a
collection:
[Link]()
[Link]()
86
YJRDMS COLLEGE OF ENGINEERING
insertOne()
[Link]({ name:
"Marsh",
age: "6 years", species:
"Dog",
ownerAddress: "380 W. Fir Ave",
chipped: true
})
insertMany()
[Link]([{ name:
"Marsh",
age: "6 years",
species: "Dog",
ownerAddress: "380 W. Fir Ave",
chipped: true},
{name: "Kitana",
age: "4 years",
species: "Cat",
ownerAddress: "521 E. Cortland", chipped:
true}])
Read operations
The read operations allow you to supply special query filters and criteria that let you specify which
documents you want. The MongoDB documentation contains more information on the available
query filters. Query modifiers may also be used to change how many results are returned.
MongoDB has two methods of reading documents from a collection:
[Link]()
[Link]()
find()
[Link]()
[Link]({"species":"Cat"})
87
YJRDMS COLLEGE OF ENGINEERING
Update operations
Like create operations, update operations operate on a single collection, and they are atomic at a single
document level. An update operation takes filters and criteria to select the documents you want to
update.
You should be careful when updating documents, as updates are permanent and can’t be rolled back.
This applies to delete operations as well.
For MongoDB CRUD, there are three different methods of updating documents:
[Link]()
[Link]()
[Link]()
updateOne()
Delete operations
Delete operations operate on a single collection, like update and create operations. Delete operations are
also atomic for a single document. You can provide delete operations with filters and criteria to
specify which documents you would like to delete from a collection. The filter options rely on the
same syntax that read operations utilize.
MongoDB has two different methods of deleting records from a collection:
[Link]()
[Link]()
deleteOne() [Link]({name:"Maki"})
{ "acknowledged" : true, "deletedCount" : 1 }
> [Link]()
{ "_id" : ObjectId("5fd98ea9ce6e8850d88270b5"), "name" : "Kitana", "age" : "4
years", "species" : "Cat", "ownerAddress" : "521 E. Cortland", "chipped" : true }
{ "_id" : ObjectId("5fd993a2ce6e8850d88270b7"), "name" : "Marsh", "age" : "5",
"species" : "Dog", "ownerAddress" : "451 W. Coffee St. A204", "chipped" : true }
{ "_id" : ObjectId("5fd993f3ce6e8850d88270b8"), "name" : "Loo", "age" : "5",
"species" : "Dog}
88
YJRDMS COLLEGE OF ENGINEERING
Here, we have created a database named as “gfgDB”. If the database doesn’t exist,
MongoDB will create the database when you store any data to it.
View all the Existing Databases
To view all existing databases in MongoDB use the “show dbs” command.
Syntax
show dbs
89
YJRDMS COLLEGE OF ENGINEERING
Output:
90
YJRDMS COLLEGE OF ENGINEERING
[Link]()
[Link](query, projection, options)
[Link]()
[Link](keys, options, commitQuorum)
91