Angular
Angular is a JS Framework for creating SPAs
An SPA has only one HTML Page, which means on the change of URL the content on the page
will change without changing the page.
The content is changed by the JS based on the request
The advantage of using SPA, is the fast response since every time the request is not send to
server but the JS will handle it on its own
JS and jQuery can be used to do the same, but when working with bigger applications writing
code will be more complex. So framework like Angular can be used
First version of Angular was Angular JS released on Oct 2010
In 2016 Angular was rereleased with completely different syntax known as Angular 2
https://www.youtube.com/playlist?list=PL1BztTYDF-QNlGo5-g65Xj1mINHYk_FM9
https://blog.angular.io/introducing-angular-v17-4d7033312e4b
https://www.youtube.com/watch?v=AGc8VVQL5sY – To Do App
Creating Angular Project
Install Node JS
Install Angular CLI
Create Project
Compile and Run
Node JS is a runtime environment for executing JS outside browser, it will provide us with tools
that will be used by Angular
Angular CLI is a command line tool used to create an Angular project, it provides a boilerplate.
npm install -g @angular/cli@latest
To create a new project
ng new project-name -–no-standalone
To run the project
ng serve
Getting Started
app-root is rendering app-component on index.html page
A component has mainly three main files, out of which the .ts one is the most important
Bootstraping
Process of initializing angular applications
ng serve: this command compiles the project and injects the bundles in index.html page
ng build: this command build the project and store the files in dist folder
Angular uses Webpack to bundle all the files
The entry point of angular application is main.ts, this is written in angular.json
Components
A component is a piece of user interface
At least one component
An angular app is tree of components
Combining all these components make an Angular UI
Creating Component
Create a .ts class and export it
Decorate the class with @Component decorator
Declare the class in main module
Creating Component using CLI
ng generate component name
Creates a component class decorated with @Component decorator
Generates the view template & stylesheet for the component
Registers the component class in main module
Selectors of Component
Components can be used as an html tag or an attribute
HTML Tag: selector : name
HTML Attribute: selector : [name]
CSS Class: selector : .name
CSS ID: selector: #name
In angular directives we use selector as attributes, other than that in most cases we use HTML
Tag selector
Data Binding
Allows us to communicate between component class and its view template and vice versa.
Pass the data from component class to view template
The data defined in component class is accessed using jinja template
One way
o Component to view
o View to Component
Two way
Component View (String Interpolation / Property binding)
View Component (Event Binding)
Component View (ngModel)
Directives
An instruction to DOM.
Manipulate DOM
Change Behavior
Add/Remove DOM Elements
Components Directive – nothing but component; has template
Attribute Directive – change the appearance or behavior of DOM element; no template
Structural Directive – add or remove DOM elements; no template; * is used for them
A class with @Directive decorator
ngFor
It is a structural directive, it iterates over a list and creates an HTML element for each item. In
very simple words it is a for each loop
*ngFor="let item of list"
ngIf
It is a structural directive, it uses a condition to add or remove a DOM element. In simple words
it is if statement
*ngIf="expression"
ngStyle
It is an attribute directive used to add inline styling to an html element dynamically based on
expression
[ngStyle]="{expression}"
ngClass
It is an attribute directive used to add CSS class to an html element dynamically based on
expression
[ngClass]="{expression}"
ng-template
It wraps an HTML snippet. This HTML snippet acts and van be used like a template and can be
rendered in the DOM
With <ng-template>, you can define template content that is only being rendered by Angular
when you, whether directly or indirectly, specifically instruct it to do so, allowing you to have
full control over how and when the content is displayed
To use the template we have to use ngTemplateOutlet
ng-container
It can hold structural directives without adding new elements to the DOM. It allows us to use
structural directives without any extra element, making sure that the only DOM changes being
applied are those dictated by the directives themselves.
ng-content
Specifies where to project content inside a component template.
ngSwitch
The [ngSwitch] directive on a container specifies an expression to match against. The
expressions to match are provided by ngSwitchCase directives on views within the container.
Custom Property Binding & @Input
Parent to Child communication
By using @Input decorator we can pass data from the parent component to its child component
Custom Event Binding & @Output
Child to Parent communication
By using @Output decorator we can pass data from the child component to its parent component
Use of EventEmitter class
Non-Related Component Communication
Combination of both – services can be used
Template Reference Variable
It is a variable that stores the reference to a DOM element, Component or directive on which it is
used
<input #phone placeholder="phone number" />
<!-- lots of other elements --> <!-- phone refers to the input
element; pass its `value` to an event handler -->
<button type="button" (click)="callPhone(phone.value)">Call</button>
#phone is a template reference variable
ViewChild Decorator
It is used to query and get a reference of DOM element in the component. It returns the first
matching
@ViewChild(‘query’) var : type
The var will have the reference of the first matching DOM element in the View
Params:
query – search query
static – true/false (resolved before/after change)
read – different token
ViewChildren Decorator
It is used to query and get a reference DOM elements in the component. It returns all the
matching elements
ContentChild Decorator
They are used to query or helps to get a reference to the projected content. Get the reference of
the projected content in the child content
Life Cycle Hooks
ngOnChanges
Change detection is a mechanism by which angular keeps the view template and component
class sync
It executed at the time of angular component creation, and whenever the @Input property
changes
Implement OnChanges
ngOnInit
It only executed once at the time after the creation and after the ngOnChanges.
Implement OnInit
ngDoCheck
It executed during every change detection cycle and after ngOnChanges and ngOnInit
Use this hook to implement a custom change detection
Implement DoChange
ngAfterContentInit
It executed after ngDoCheck and when the components projected content is fully initialized
Implement AfterContentInit
ngAfterContentChecked
It executed after ngAfterContentInit and after every change detection cycle after the initialization
of projected content
Implement AfterContentChecked
Custom Directives
Attribute
@Directive({
selector: '[selector]'
})
export class Name {
constructor(element: ElementRef){
//code
}
}
Register this directive in app module before using it
- Native element property of elemntRef is not recommended
- Renderer 2 is the solution, it provides the access to DOM with a layer of abstraction between
the DOM element and component code.
@HostListner
This decorator listens to a DOM event on the host element and it reacts to that event by
executing an event handler method
@HostListener('event-name')
@HostBinding
This decorator binds host event property to a property of a directive or a component class
@HostBinding('property')
Conditional Attribute Directive
It helps applying the change based on condition to a DOM element
Services
A typescript class which contains a piece of code that can be reused throughout the angular app.
It provides reusability.
Dependency Injection
Allow classes to configure dependencies that they need. It is a relationship between two
components where one component relies on the other to work
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Service {
constructor() { }
}