angularv18 (1)
angularv18 (1)
1
Angular
Angular is a development platform, built on TypeScript. As a platform, Angular includes:
With Angular, you're taking advantage of a platform that can scale from single-developer projects to enterprise-level
applications. Angular is designed to make updating as straightforward as possible, so take advantage of the latest
developments with minimal effort. Best of all, the Angular ecosystem consists of a diverse group of over 1.7 million developers,
library authors, and content creators.
According to the 2022 StackOverflow survey, 23 percent of software engineers apply the framework to create user interfaces.
2
History of Angular
Its history traces back to 2009 when Misko Hevery and Adam Abrons, Google engineers, developed the framework known as
AngularJS and officially released it in 2010.
AngularJS revolutionized web development by providing a convenient way to build dynamic, single-page applications (SPAs).
Designing complex dynamic web pages with pure or vanilla JavaScript is time-consuming. Not to mention that, in big projects
involving many programmers, the front-end is a challenge to understand and maintain. So, the key idea behind AngularJS was
to simplify SPA development by introducing several considerable advantages.
MVC architecture: AngularJS divides your web app into three distinct parts — Model (data), View (the UI layer), and Controller
(business logic). The three units can be developed in parallel and separately tested. As a result, the code becomes easier to
understand, maintain, and extend.
Two-way data binding: The JavaScript framework synchronizes the Model and the View by applying a two-way data binding
technique. As the data in the Model changes, the View does too. This allows engineers to reduce development time as it
doesn’t require writing additional code to provide continual View and Model synchronization.
3
History of Angular
Dependency injection (DI): AngularJS comes with a built-in mechanism to pass (inject) dependencies — or rules defining how
pieces of code interact with each other and behave under certain conditions — instead of creating them inside the
components. This enables developers to change or configure dependencies without altering an app module as well as reuse
them across multiple modules. All in all, DI simplifies testing and contributes to the reusability and maintainability of app
components.
Featuring a prominent set of benefits, AngularJS quickly grew in popularity. But unfortunately for the framework, technologies
developed even faster. Before long, the platform stopped meeting the rising requirements of the web and lost its position to
newer competitors. So, in 2014, Google decided to completely rewrite it.
For several years, AngularJS has existed side by side with its successor simply named Angular. But in 2022, it, at last, reaches the
end of life, i.e., the community will no longer maintain the framework. That said, devoted users can still find support from third
parties, and AngularJS code will remain on GitHub.
4
AngularJS vs Angular
In September 2016, Google released Angular 2. The difference between the old AngularJS and the new version was so radical
that you couldn’t just update from one to the other. The main changes are as follows.
TypeScript instead of JavaScript: Unlike its JS-based predecessor, Angular uses TypeScript.
Better performance: Both AngularJS and Angular significantly reduce development time. However, due to the component-
based architecture and more effective data binding, Angular apps can be five times faster than AngularJS.
Introducing CLI AngularJS doesn’t have its own command line interface (CLI). Angular 2+, on the other hand, comes with a CLI
that allows for quick generation of components, services, directives, etc.
Mobile-friendliness AngularJS was not designed with mobile browsers in mind. When developing Angular, Google took into
account this gap so the new framework got the support for mobile web and native mobile apps.
5
Setting up the development environment
You can use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing
development tasks such as testing, bundling, and deployment.
To install the Angular CLI, open a terminal window and run the following command: npm install -g @angular/cli
Run the CLI command ng new and provide the name my-app: ng new my-app
The ng new command prompts you for information about features to include in the initial app. Accept the defaults by
pressing the Enter or Return key.
The Angular CLI includes a server, for you to build and serve your app locally.
cd my-app
ng serve --open
6
The npm start command will also launches the server, watches your files, and rebuilds the app as you make changes to those
files.
If the installation and setup was successful, you should see a page similar to the following.
7
CLI commands
To view all available commands, we run:
ng help
• build (b): Compiles an Angular application and outputs generated files in a predefined folder.
• serve (s): Builds an Angular application and serves it using a pre-configured web server.
• deploy: Deploys an Angular application to a web-hosting provider. You can choose from a collection of providers included in
the Angular CLI.
• completion: Enables auto-complete for Angular CLI commands through the terminal.
9
Project Architecture
.vscode: Includes VS Code configuration files
node_modules: Includes npm packages needed for development and running the Angular application
.gitignore: Specifies files and folders that Git should not track
package.json and package-lock.json: Provide definitions of npm packages, along with their exact versions, which are
needed to develop, test, and run the Angular application
README.md: A README file that is automatically generated from the Angular CLI
app: Contains all the Angular-related files of the application. You interact with this folder most of the time during
development.
favicon.ico: The icon displayed in the tab of your browser, along with the page title.
styles.css: Contains application-wide styles. These are CSS styles that apply globally to the Angular application. The
extension of this file depends on the stylesheet format you choose when creating the application
11
Project Architecture
The app folder contains the actual source code we write for our application. Developers spend most of their time inside that
folder. The Angular application that is created automatically from the Angular CLI contains the following files:
12
Components
The fundamental building block for creating applications in Angular.
Components provide structure for organizing your project into easy-to-understand parts with clear responsibilities so that your
code is maintainable and scalable.
13
Components
Here is a simplified example of a component
// todo-list-item.component.ts
@Component({
standalone: true,
selector: 'todo-list-item',
template: `
<li>(TODO) Read Angular Essentials Guide</li>
`,
styles: `
li {
color: red;
font-weight: 300;
}
`,
})
export class TodoListItem {
/* Component behavior is defined in here */
}
14
Separating HTML and CSS into separate files
For teams that prefer managing their HTML and/or CSS in separate files, Angular provides two additional properties:
templateUrl and styleUrl .
// todo-list-item.component.ts
@Component({
standalone: true,
selector: 'todo-list-item',
templateUrl: './todo-list-item.component.html',
styleUrl: './todo-list-item.component.css',
})
export class TodoListItem {
/* Component behavior is defined in here */
}
/* todo-list-item.component.css */
li {
color: red;
font-weight: 300;
} 15
Using a component
One advantage of component architecture is that your application is modular. In other words, components can be used in
other components.
// todo-list.component.ts
import {TodoListItem} from './todo-list-item.component.ts';
@Component({
standalone: true,
imports: [TodoListItem],
template: `
<ul>
<todo-list-item></todo-list-item>
</ul>
`,
})
export class TodoList {}
16
Standalone components
A standalone component is a component that sets standalone: true in its component metadata. Standalone components
directly import other components, directives, and pipes used in their templates
17
Component selectors
Every component defines a CSS selector that determines how the component is used:
@Component({
selector: 'profile-photo',
...
})
export class ProfilePhoto { }
You use a component by creating a matching HTML element in the templates of other components:
@Component({
template: `
<profile-photo />
<button>Upload a new profile photo</button>`,
...,
})
export class UserProfile { }
18
Templates
In Angular, a template is a blueprint for a fragment of a user interface (UI). Templates are written in HTML, and special syntax
can be used within a template to build on many of Angular's features.
Displaying values with interpolation: Interpolation refers to embedding expressions into marked up text. By default,
interpolation uses the double curly braces {{ and }} as delimiters.
<p>{{title}}</p>
<div><img alt="item" src="{{itemImageUrl}}"></div>
19
Directives
Angular directives are HTML attributes that extend the behavior or the appearance of a standard HTML element. When we
apply a directive to an HTML element or even an Angular component, we can add custom behavior to it or alter its appearance.
There are three types of directives:
20
Structural Directives
The Angular framework includes a set of ready-made structural directives that we can start using
straight away in our applications:
21
ngIf
To use NgIf , add it to the component's imports list.
<div *ngIf="name">
<h2>Product Details</h2>
<h3>{{name}}</h3>
<button (click)="buy()">Buy Now</button>
</div>
22
Angular embeds the HTML element marked with the *ngIf directive into an ng-template element, which is used later to render
the actual content on the screen. The ng-template is neither added to the DOM tree nor rendered on screen. Instead, it acts as
a wrapper to group other HTML elements. These elements are not rendered automatically on the screen, but structural
directives trigger them.
<p *ngIf="selectedProduct">
A product is selected
</p>
<p *ngIf="!selectedProduct">No product selected!</p>
23
ngFor
To use NgFor , add it to the component's imports list.
The ngFor directive allows us to loop through a collection of items and render a template for each one, where we can define
convenient placeholders to interpolate item data.
<ul>
<li *ngFor="let product of products" >
{{product}}
</li>
</ul>
It is also possible to keep track of other useful properties as well. We can use the extended version of the *ngFor directive using
the following syntax:
24
The variable is a template input variable that we can reference later in our template. The property can have the following
values:
index: Indicates the index of the item in the array, starting at 0 (number)
first/last: Indicates whether the current item is the first or last item in the array
(boolean)
even/odd: Indicates whether the index of the item in the array is even or odd (Boolean)
<ul>
<li *ngFor="let product of products; let i=index">
{{i+1}}. {{product}}
</li>
</ul>
25
ngSwitch
To use the directives, add the NgSwitch , NgSwitchCase and NgSwitchDefault to the component's imports list.
It is used to switch between templates and display each one depending on a defined value. You can think of ngSwitch as like an
ordinary switch statement that we use in other programming languages. It consists of a set of other directives:
[ngSwitch]: Defines the property that we want to check when applying the directive
*ngSwitchCase: Adds or removes a template from the DOM tree depending on the value of the property defined in the
[ngSwitch] statement
*ngSwitchDefault: Adds a template to the DOM tree if the value of the property defined in the [ngSwitch] directive does
not meet any *ngSwitchCase statement
26
<div *ngIf="name">
<h2>Product Details</h2>
<h3>{{name}}</h3>
<div [ngSwitch]="name">
<p *ngSwitchCase="'Webcam'">
Product is used for video
</p>
<p *ngSwitchCase="'Microphone'">
Product is used for audio
</p>
<p *ngSwitchDefault>Product is for general use</p>
</div>
<button (click)="buy()">Buy Now</button>
</div>
27
Binding
In an Angular template, a binding creates a live connection between a part of the UI created from a template (a DOM element,
directive, or component) and the model (the component instance to which the template belongs).
This connection can be used to synchronize the view with the model, to notify the model when an event or user action takes
place in the view, or both.
Text interpolations
Property binding
Attribute binding
Event binding
Two-way binding
28
Property binding
Property binding in Angular helps you set values for properties of HTML elements or directives. Use property binding to do
things such as toggle button features, set paths programmatically, and share values between components.
To bind to an element's property, enclose it in square brackets, [], which identifies the property as a target property.
29
Attribute Binding
Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility,
style your application dynamically, and manage multiple CSS classes or styles simultaneously.
Attribute binding syntax resembles property binding, but instead of an element property between brackets, you precede the
name of the attribute with the prefix attr, followed by a dot. Then, you set the attribute value with an expression that resolves
to a string.
<p [attr.attribute-you-are-targeting]="expression"></p>
When the expression resolves to null or undefined, Angular removes the attribute altogether.
30
Class and style binding
Use class and style bindings to add and remove CSS class names from an element's class attribute and to set styles dynamically.
[class.sale]="onSale"
Angular adds the class when the bound expression, onSale is truthy, and it removes the class when the expression is falsy
To create a single style binding, use the prefix style followed by a dot and the name of the CSS style.
<nav [style.background-color]="expression"></nav>
31
Event Binding
Event binding lets you listen for and respond to user actions such as keystrokes, mouse movements, clicks, and touches.
<button (click)="onSave()">Save</button>
32
Two way binding
Angular, two-way data binding is typically used with form controls, allowing you to bind the value of an input field to a
property in your component.
Property Binding [property] : Binds a property of a DOM element to a property in your component.
Event Binding (event) : Listens for events emitted by a DOM element and triggers a method in your component.
By combining these two bindings with [(ngModel)] , you create a two-way binding, where changes in the input field
immediately update the component property, and changes to the component property immediately update the input field.
33
TP
Create a data model of the class Book
Each book has a name property (string) and isRead property (boolean)
The class will be created in a new folder called shared and export it
In app.component.ts import the book class
Create a property called books in the AppComponent class
This property is an array with three books
In app.component.html list through the books list
When the list is empty a message should show instead
Have a checkbox checked before every book if the book is read
34