0% found this document useful (0 votes)
138 views39 pages

angular ppt

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
138 views39 pages

angular ppt

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 39

commands

Command Purpose
npm install -g @angular/cli Installs Angular CLI globally
ng new <project name> Creates a new Angular application
Builds and runs the application on lite-server and launches
ng serve --open
a browser
Creates a class, component, directive, interface, module,
ng generate <name>
pipe, and service
ng build Builds the application
ng update @angular/cli
Updates Angular to latest version
@angular/core

File / Folder Purpose


Node.js creates this folder and puts all npm modules installed as listed in
node_modules/
package.json
src/ All application-related files will be stored inside it
Configuration file for Angular CLI where we set several defaults and also
angular.json
configure what files to be included during project build
This is a node configuration file that contains all dependencies required for
package.json
Angular
This is the Typescript configuration file where we can configure compiler
tsconfig.json
options
From Angular version 13.0.0, .angular folder is generated in the root. This
.angular
folder caches the builds and is ignored by git.
Type the following command to run the application. This will open a browser with the default
port as 4200.

1. D:\mCart>ng serve --open


Why Components in Angular?

Creating a Component
 Open Visual Studio Code IDE. Go to the File menu and select the "Open Folder"
option. Select the MyApp folder you have created earlier.
 Observe for our AppComponent you have below files
o app.component.ts
o app.component.html
o app.component.css
 Let us explore each one of them
 Go to src folder-> app -> open app.component.ts file
 Observe the following code

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

2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
7. export class AppComponent {
8. title = 'AngDemo';
9. }
Line 2: Adds component decorator to the class which makes the class a component
Line 3: Specifies the tag name to be used in the HTML page to load the component
Line 4: Specifies the template or HTML file to be rendered when the component is loaded in
the HTML page. The template represents the view to be displayed
Line 5: Specifies the stylesheet file which contains CSS styles to be applied to the template.
Line 7: Every component is a class (AppComponent, here) and export is used to make it
accessible in other components
Line 8: Creates a property with the name title and initializes it to value 'AngDemo'

 Open app.component.html from the app folder and observe the following code
snippet in that file

<span>{{ title }} app is running!</span>

Line 1: Accessing the class property by placing property called title inside {{ }}. This is
called interpolation which is one of the data binding mechanisms to access class properties
inside the template.
Best Practices - Coding Style Rules
Always write one component per file. This will make it easier to read, maintain, and
avoid hidden bugs. It makes code reusable and less mistake-prone.
Always define small functions which makes it easier to read and maintain
The recommended pattern for file naming convention is feature.type.ts. For example, to
create a component for Login, the recommended filename is login.component.ts. Use the
upper camel case for class names. For example, LoginComponent.
Use a dashed case for the selectors of a component to keep the names consistent for all
custom elements. Ex: app-root

Modules
 Modules in Angular are used to organize the application. It sets the execution
context of an Angular application.
 A module in Angular is a class with the @NgModule decorator added to it.
@NgModule metadata will contain the declarations of components, pipes,
directives, services that are to be used across the application.
 Every Angular application should have one root module which is loaded first to
launch the application.
 Submodules should be configured in the root module.
Root Module
In the app.module.ts file placed under the app folder, you have the following code:

1. import { BrowserModule } from '@angular/platform-browser';

2. import { NgModule } from '@angular/core';

3. import { AppRoutingModule } from './app-routing.module';

4. import { AppComponent } from './app.component';

5. @NgModule({

6. declarations: [

7. AppComponent

8. ],

9. imports: [

10. BrowserModule,

11. AppRoutingModule

12. ],

13. providers: [],

14. bootstrap: [AppComponent]

15. })

16. export class AppModule { }

Line 1: imports BrowserModule class which is needed to run the application inside the
browser
Line 2: imports NgModule class to define metadata of the module
Line 4: imports AppComponent class from app.component.ts file. No need to mention the .ts
extension as Angular by default considers the file as a .ts file
Line 6: declarations property should contain all user-defined components, directives, pipes
classes to be used across the application. We have added our AppComponent class here
Line 9: imports property should contain all module classes to be used across the application
Line 13: providers' property should contain all service classes. You will learn about the
services later in this course
Line 14: bootstrap declaration should contain the root component to load. In this example,
AppComponent is the root component that will be loaded in the HTML page
Bootstrapping Root Module
In the main.ts file placed under the src folder, observe the following code:

1. import { enableProdMode } from '@angular/core';

2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

3. import { AppModule } from './app/app.module';

4. import { environment } from './environments/environment';

5. if (environment.production) {

6. enableProdMode();

7. }

8. platformBrowserDynamic().bootstrapModule(AppModule)

9. .catch(err => console.error(err));e 1: imports enableProdMode from the core module

Line 2: import platformBrowserDynamic class which is used to compile the application based
on the browser platform
Line 3: import AppModule which is the root module to bootstrap
Line 4: imports environment which is used to check whether the type of environment is
production or development
Line 5: checks if you are working in a production environment or not
Line 6: enableProdMode() will enable production mode which will run the application faster
Line 8: bootstrapModule() method accepts root module name as a parameter which will load
the given module i.e., AppModule after compilation
Loading root component in HTML Page
Open index.html under the src folder.

1. <!doctype html>

2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>MyApp</title>
6. <base href="/">
7. <meta name="viewport" content="width=device-width, initial-scale=1">
8. <link rel="icon" type="image/x-icon" href="favicon.ico">
9. </head>
10. <body>
11. <app-root></app-root>
12. </body>
13. </html>
Line 11: loads the root component in the HTML page. app-root is the selector name given to
the component. This will execute the component and renders the template inside the browser.
Best Practices - Coding Style Rules
Always add a Module keyword to the end of the module class name which provides a
consistent way to quickly identify the modules. Ex: AppModule.
Filename convention for modules should end with module.ts
Always name the module with the feature name and the folder it resides in which
provides a way to easily identify it.
Executing Angular Application
Execute the application and check the output.
 Open terminal in Visual Studio Code IDE by selecting View Menu -> Integrated
Terminal.
 Type the following command to run the application

1. D:\MyApp>ng serve --open

 ng serve will build and run the application


 --open option will show the output by opening a browser automatically with the
default port.
Note: If you get an error in the terminal like 'ng is not recognized', use the Node.js command
prompt to run this command.
 Use the following command to change the port number if another application is
running on the default port(4200)

1. D:\MyApp>ng serve --open --port 3000

Following is the output of the MyApp Application

demo
Ng serve --open
Templates Basics

Introduction to Templates
 Templates separate the view layer from the rest of the framework.
 You can change the view layer without breaking the application.
 Templates in Angular represents a view and its role is to display data and change the
data whenever an event occurs
 The default language for templates is HTML
Creating a template
Template can be defined in two ways:
 Inline Template
 External Template
Inline Template
You can create an inline template in a component class itself using the template property of
the @Component decorator.
app.component.ts

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

2. @Component({

3. selector: 'app-root',
4. template: `

5. <h1> Welcome </h1>

6. <h2> Course Name: {{ courseName }}</h2>

7. `,

8. styleUrls: ['./app.component.css']

9. })

10. export class AppComponent {

11. courseName = "Angular";

12. }

Line 5-8: You can even write HTML code inside the component using the template property.
Use backtick character (`) for multi-line strings.
Output:

External Template
 By default, Angular CLI uses the external template.
 It binds the external template with a component using templateUrl option.

Example
app.component.html

1. <h1> Welcome </h1>


2. <h2> Course Name: {{ courseName }}</h2>

app.component.ts

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

2. @Component({

3. selector: 'app-root',

4. templateUrl:'./app.component.html',

5. styleUrls: ['./app.component.css']

6. })
7. export class AppComponent {

8. courseName = "Angular";

9. }

Line 4: templateUrl property is used to bind an external template file with the component
Output:

Demo
Consider HelloComponent created in the previous demo. Now use the inline template option.
Problem Statement: Moving HTML code of HelloComponent to the component class using
an inline template which should display the following output

Click here to run the demo on Templates.


1. Copy the code from hello.component.html and paste it in hello.component.ts (Line 5 to
9)

1. import { Component, OnInit } from '@angular/core';

2. @Component({
3. selector: 'app-hello',
4. template:`
5. <p>
6. Hello {{ courseName }}
7. </p>
8. `,
9. styleUrls: ['./hello.component.css']
10. })
11. export class HelloComponent implements OnInit {
12. courseName = "Angular";
13. constructor() { }
14. ngOnInit() {
15. }
16. }

1. Save the file and observe the output in the browser


Elements of Template
The basic elements of template syntax:
 HTML
 Interpolation
 Template Expressions
 Template Statements
HTML
Angular uses HTML as a template language. In the below example, the template contains
pure HTML code.
Interpolation
Interpolation is one of the forms of data binding where component’s data can be accessed in a
template. For interpolation, double curly braces {{ }} is used.
Template Expressions
 The text inside {{ }} is called as template expression.

1. {{ expression }}

 Angular first evaluates the expression and returns the result as a string. The
scope of a template expression is a component instance.
 That means, if you write {{ courseName }}, courseName should be the property of
the component to which this template is bound.
Template Statement
 Template Statements are the statements that respond to a user event.

1. (event) = statement

 For example (click) = "changeName()"


 This is called event binding. In Angular, all events should be placed in ( ).
Example:
app.component.ts

1. ...

2. export class AppComponent {

3. courseName = "Angular";

4.

5. changeName() {

6. this.courseName = "TypeScript";

7. }

8. }

Line 5-7: changeName is a method of AppComponent class where you are changing
courseName property value to "TypeScript"
app.component.html

1. <h1> Welcome </h1>

2. <h2> Course Name: {{ courseName }}</h2>

3. <p (click)="changeName()">Click here to change</p>


Line 3: changeName() method is bound to click event which will be invoked on click of a
paragraph at run time. This is called event binding.

Output:
When a user clicks on the paragraph, the course name will be changed to 'Typescript'.

Demo : Elements of Template


Highlights:
 Understanding the template elements
 Responding to user actions
Demosteps:
Problem Statement: Adding an event to the hello component template and when it is
clicked, it should change the courseName as shown below

Course Name: TypeScript automatic change

1. Open hello.component.ts, add a method called changeName() as shown below in Line 12-
14. Also, use external template hello.component.html.

1. import { Component, OnInit } from '@angular/core';

2. @Component({
3. selector: 'app-hello',
4. templateUrl: "./hello.component.html",
5. styleUrls: ['./hello.component.css']
6. })
7. export class HelloComponent implements OnInit {
8. courseName = "Angular";
9. constructor() { }
10. ngOnInit() {
11. }
12. changeName() {
13. this.courseName = "TypeScript";
14. }
15. }

2. Open hello.component.html and add a paragraph and bind it with changeName() method
as shown in Line 3
1. <h1>Welcome</h1>

2. <h2>Course Name: {{ courseName }}</h2>


3. <p (click)="changeName()">Click here to change</p>

3. Save the files and check the output in the browser


Change Detection
How does Angular detect the changes and update the application at the respective
places?
Angular uses its change detection mechanism to detect the changes and update the
application at the respective places. Angular applications run faster than Angular 1.x
applications due to the improved change detection mechanism.
What is the change detection mechanism, and how it helps to run Angular applications
so fast?
 Change Detection is a process in Angular that keeps views in sync
with the models.
 In Angular, the flow is unidirectional from top to bottom in a
component tree. A change in a web application can be caused by
events, Ajax calls, and timers which are all asynchronous.
Who informs Angular about the changes?
 Zones inform Angular about the changes in the application. It
automatically detects all asynchronous actions at run time in the application.
What happens when a change is detected?
What does Angular do when a change is detected?
 Angular runs a change detector algorithm on each component from top to
bottom in the component tree. This change detector algorithm is automatically
generated at run time which will check and update the changes at appropriate places
in the component tree.
 Angular is very fast though it goes through all components from top to bottom for
every single event as it generates VM-friendly code. Due to this, Angular
can perform hundreds of thousands of checks in a few milliseconds.

Structural Directives
 Directives are used to change the behavior of components or elements. It can be
used in the form of HTML attributes.
 You can create directives using classes attached with @Directive decorator which
adds metadata to the class.
Why Directives?

 It modify the DOM elements

 It creates reusable and independent code


 It is used to create custom elements to implement the required functionality
Types of Directives
There are three types of directives available in Angular

Components
 Components are directives with a template or view.
 @Component decorator is actually @Directive with templates

Structural Directives
 A Structural directive changes the DOM layout by adding and removing DOM
elements.

1. *directive-name = expression

 Angular has few built-in structural directives such as:


o ngIf

o ngFor

o ngSwitch
ngIf
ngIf directive renders components or elements conditionally based on whether or not an
expression is true or false.
Syntax:

1. *ngIf = "expression"

ngIf directive removes the element from the DOM tree.


Example:

app.component.ts

1. ...

2. export class AppComponent {

3. isAuthenticated!: boolean;
4. submitted = false;

5. userName!: string;

6. onSubmit(name: string, password: string) {

7. this.submitted = true;

8. this.userName = name;

9. if (name === "admin" && password === "admin") {

10. this.isAuthenticated = true;

11. } else {

12. this.isAuthenticated = false;

13. }

14. }--

15. }

Line 5: Notice the use of ! with the property username. This is called adding definite
assertion for variables(is a feature that allows a ! to be placed after instance property
and variable declarations to relay to TypeScript that a variable is indeed assigned for
all intents and purposes, even if TypeScript’s analyses cannot detect so.) during
declaration.

definite assertion for variables example in TypeScript


let x: number;
initialize();
console.log(x + x);
// ~ ~
// Error! Variable 'x' is used before being assigned.
function initialize() {
x = 10;
}

With definite assignment assertions, we can assert that x is really


assigned by appending an ! to its declaration:

// Notice the '!'


let x!: number;
initialize();
// No error!
console.log(x + x);
function initialize() {
x = 10;
}

In a sense, the definite assignment assertion operator is the dual of the


non-null assertion operator (in which expressions are post-fixed with a !),
which we could also have used in the example.

let x: number;
initialize();
// No error!
console.log(x! + x!);
function initialize() {
x = 10;

In our example, we knew that all uses of x would be initialized so it makes


more sense to use definite assignment assertions than non-null
assertions.

Definite assertion for variables


Angular CLI creates all new workspaces and projects with strict mode enabled. This leads to
an improved compile time check for properties. If any property is not initialized either by
providing a default value or by initializing within the constructor or if a parameter is not
mapped to a property, the below error gets generated:

property <<property>> has no initializer and is not definitely assigned in the constructor.
This is known as a .00d`10..Definite assignment error because there is no definite assignment
for that property. The correct fix to this is to assign the property with a value in the
constructor. An alternate is to permit the property with no definite assignment by using the
definite assignment assertion. You can do that by adding ! to the property name.
userName in Line 5 of the above code doesn't have a value initialized and hence the use of !.
Line 7 -14: onSubmit method is invoked when the user clicks on the submit button in the
template. This method checks the username and password values entered are correct or not
and accordingly assigns a boolean value to isAuthenticated variable.
app.component.html

1. <div *ngIf="!submitted">

2. ...

3. <button (click)="onSubmit(username.value, password.value)">Login</button>

4. </div>

5. <div *ngIf="submitted">
6. <div *ngIf="isAuthenticated; else failureMsg">

7. <h4>Welcome {{ userName }}</h4>

8. </div>

9. <ng-template #failureMsg>

10. <h4>Invalid Login !!! Please try again...</h4>

11. </ng-template>

12. <button type="button" (click)="submitted = false">Back</button>

13. </div>

Line 7: Username will be displayed if 'isAuthenticated' property value is true otherwise it will
be an error message.
Output:
After entering the correct credentials and clicking on the Login button.

After entering incorrect credentials and clicking on the Login button.

Demo : ngIf
Highlights:
 Understanding ngIf directive
 Invoking a directive on user's action
Demosteps:
Problem Statement: Create a login form with username and password fields. If the user
enters the correct credentials, it should render a "Welcome <<username>>" message
otherwise it should render "Invalid Login!!! Please try again..." message as shown below:
Click here to run the demo on Structural Directive.
1. Open app.component.ts and write the following code:

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

2. @Component({

3. selector: 'app-root',

4. templateUrl: './app.component.html',

5. styleUrls: ['./app.component.css'],

6. })

7. export class AppComponent {

8. isAuthenticated!: boolean;

9. submitted = false;

10. userName!: string;

11. onSubmit(name: string, password: string) {

12. this.submitted = true;

13. this.userName = name;

14. if (name === 'admin' && password === 'admin') {

15. this.isAuthenticated = true;

16. } else {

17. this.isAuthenticated = false;

18. }

19. }

20. }

2. Write the below-given code in app.component.html:


1. <div *ngIf="!submitted">

2. <form>

3. <label>User Name</label>

4. <input type="text" #username /><br /><br />

5. <label for="password">Password</label>

6. <input type="password" name="password" #password /><br />

7. </form>

8. <button (click)="onSubmit(username.value, password.value)">Login</button>

9. </div>

10. <div *ngIf="submitted">

11. <div *ngIf="isAuthenticated; else failureMsg">

12. <h4>Welcome {{ userName }}</h4>

13. </div>

14. <ng-template #failureMsg>

15. <h4>Invalid Login !!! Please try again...</h4>

16. </ng-template>

17. <button type="button" (click)="submitted = false">Back</button>

18. </div>

3. Add AppComponent to the bootstrap property in the root module file i.e., app.module.ts

1. import { BrowserModule } from '@angular/platform-browser';

2. import { NgModule } from '@angular/core';

3. import { AppComponent } from './app.component';

4. @NgModule({

5. declarations: [
6. AppComponent

7. ],

8. imports: [

9. BrowserModule

10. ],

11. providers: [],

12. bootstrap: [AppComponent]

13. })

14. export class AppModule { }

4. Ensure the index.html displays app-root.

1. <!doctype html>

2. <html lang="en">

3. <head>

4. <meta charset="utf-8">

5. <title>MyApp</title>

6. <base href="/">

7. <meta name="viewport" content="width=device-width, initial-scale=1">

8. <link rel="icon" type="image/x-icon" href="favicon.ico">

9. </head>

10. <body>

11. <app-root></app-root>

12. </body>

13. </html>

5. Save the files and check the output in the browser.


ngFor Directive
ngFor directive is used to iterate over-collection of data i.e., arrays
Syntax:

1. *ngFor = "expression"

Example:
app.component.ts

1. ...

2. export class AppComponent {

3. courses: any[] = [

4. { id: 1, name: "TypeScript" },

5. { id: 2, name: "Angular" },

6. { id: 3, name: "Node JS" },

7. { id: 1, name: "TypeScript" }

8. ];

9. }

Line 3-8: Creating an array of objects


app.component.html

1. <ul>

2. <li *ngFor="let course of courses; let i = index">

3. {{i}} - {{ course.name }}

4. </li>

5. </ul>

Line 2: ngFor iterates over courses array and displays the value of name property of each
course. It also stores the index of each item in a variable called i
Line 3: {{ i }} displays the index of each course and course.name displays the name property
value of each course
Output:

Demo : ngFor
Highlights:
 Understanding ngFor directive
 Iteration of an array using ngFor directive
Demosteps:
Problem Statement: Creating a courses array and rendering it in the template using ngFor
directive in a list format as shown below
0-TypeScript
1-Angular
2-Node JS
3-TypeScript
1. Write the below-given code in app.component.ts

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

2. @Component({

3. selector: 'app-root',

4. templateUrl: './app.component.html',

5. styleUrls: ['./app.component.css']

6. })

7. export class AppComponent {

8. courses: any[] = [

9. { id: 1, name: 'TypeScript' },

10. { id: 2, name: 'Angular' },

11. { id: 3, name: 'Node JS' },

12. { id: 1, name: 'TypeScript' }

13. ];

14. }

2. Write the below-given code in app.component.html

1. <ul>

2. <li *ngFor="let course of courses; let i = index">

3. {{ i }} - {{ course.name }}

4. </li>
5. </ul>

3. Save the files and check the output in the browser


ngSwitch Directive
 ngSwitch adds or removes DOM trees when their expressions match the switch
expression. Its syntax is comprised of two directives, an attribute directive, and a
structural directive.
 It is very similar to a switch statement in JavaScript and other programming
languages.
Example:
app.component.ts

1. ...

2. export class AppComponent {

3. choice = 0;

4.

5. nextChoice() {

6. this.choice++;

7. }

8. }

Line 3: Creates a choice property and initializes it to zero


Line 5-7: nextChoice() increments the choice when invoked

app.component.html

1. ...

2. <div [ngSwitch]="choice">

3. <p *ngSwitchCase="1">First Choice</p>

4. <p *ngSwitchCase="2">Second Choice</p>

5. <p *ngSwitchCase="3">Third Choice</p>

6. <p *ngSwitchCase="2">Second Choice Again</p>

7. <p *ngSwitchDefault>Default Choice</p>

8. </div>
9. ...

Line 2: ngSwitch takes the value and based upon the value inside the choice property, it
executes *ngSwitchCase. Paragraph elements will be added/removed from the DOM based
on the value passed to the switch case.
Output:

Demo : ngSwitch
Highlights:
 Understanding ngSwitch directive
 Invoking a directive on user's action
Demosteps:
Problem Statement: Displaying the correct option based on the value passed to ngSwitch
directive as shown below:

Write the below-given code in app.component.ts

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

2. @Component({

3. selector: 'app-root',

4. templateUrl: './app.component.html',

5. styleUrls: ['./app.component.css']

6. })

7. export class AppComponent {

8. choice = 0;

9. nextChoice() {

10. this.choice++;
11. }

12. }

2. Write the below-given code in app.component.html

1. <h4>

2. Current choice is {{ choice }}

3. </h4>

4. <div [ngSwitch]="choice">

5. <p *ngSwitchCase="1">First Choice</p>

6. <p *ngSwitchCase="2">Second Choice</p>

7. <p *ngSwitchCase="3">Third Choice</p>

8. <p *ngSwitchCase="2">Second Choice Again</p>

9. <p *ngSwitchDefault>Default Choice</p>

10. </div>

11. <div>

12. <button (click)="nextChoice()">

13. Next Choice

14. </button>

15. </div>

3. Save the files and check the output in the browser


Custom Structural Directive
You can create custom structural directives when there is no built-in directive available for
the required functionality. For example, when you want to manipulate the DOM in a
particular way which is different from how the built-in structural directives manipulate.

You might also like