angular ppt
angular ppt
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
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
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
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:
5. @NgModule({
6. declarations: [
7. AppComponent
8. ],
9. imports: [
10. BrowserModule,
11. AppRoutingModule
12. ],
15. })
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:
5. if (environment.production) {
6. enableProdMode();
7. }
8. platformBrowserDynamic().bootstrapModule(AppModule)
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
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
2. @Component({
3. selector: 'app-root',
4. template: `
7. `,
8. styleUrls: ['./app.component.css']
9. })
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
app.component.ts
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
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. {{ 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
1. ...
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
Output:
When a user clicks on the paragraph, the course name will be changed to 'Typescript'.
1. Open hello.component.ts, add a method called changeName() as shown below in Line 12-
14. Also, use external template hello.component.html.
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>
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?
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
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"
app.component.ts
1. ...
3. isAuthenticated!: boolean;
4. submitted = false;
5. userName!: string;
7. this.submitted = true;
8. this.userName = name;
11. } else {
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.
let x: number;
initialize();
// No error!
console.log(x! + x!);
function initialize() {
x = 10;
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. ...
4. </div>
5. <div *ngIf="submitted">
6. <div *ngIf="isAuthenticated; else failureMsg">
8. </div>
9. <ng-template #failureMsg>
11. </ng-template>
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.
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:
2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css'],
6. })
8. isAuthenticated!: boolean;
9. submitted = false;
16. } else {
18. }
19. }
20. }
2. <form>
3. <label>User Name</label>
5. <label for="password">Password</label>
7. </form>
9. </div>
13. </div>
16. </ng-template>
18. </div>
3. Add AppComponent to the bootstrap property in the root module file i.e., app.module.ts
4. @NgModule({
5. declarations: [
6. AppComponent
7. ],
8. imports: [
9. BrowserModule
10. ],
13. })
1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>MyApp</title>
6. <base href="/">
9. </head>
10. <body>
11. <app-root></app-root>
12. </body>
13. </html>
1. *ngFor = "expression"
Example:
app.component.ts
1. ...
3. courses: any[] = [
8. ];
9. }
1. <ul>
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
2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
8. courses: any[] = [
13. ];
14. }
1. <ul>
3. {{ i }} - {{ course.name }}
4. </li>
5. </ul>
1. ...
3. choice = 0;
4.
5. nextChoice() {
6. this.choice++;
7. }
8. }
app.component.html
1. ...
2. <div [ngSwitch]="choice">
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:
2. @Component({
3. selector: 'app-root',
4. templateUrl: './app.component.html',
5. styleUrls: ['./app.component.css']
6. })
8. choice = 0;
9. nextChoice() {
10. this.choice++;
11. }
12. }
1. <h4>
3. </h4>
4. <div [ngSwitch]="choice">
10. </div>
11. <div>
14. </button>
15. </div>