Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
55 views

Angular Notes

Uploaded by

niteshsingh82910
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Angular Notes

Uploaded by

niteshsingh82910
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Angular Notes

 The benefit of converting TS & HTML in JavaScript code is the DOM


elements can be dynamically manipulated by the script based on the
changes to application data.
Angular architecture
 First, there will be a component that contains application data and application
logic in the form of event handler methods, which responds to the user
actions.
 Every component has a template. The template contains HTML logic, i.e.
design logic, to describe the views.
 The component and the template exchange information as long as the
application executes by using data binding relationship.
 For example, there is a property called PersonName, in the component and
that is a textbox in the template, which has data binding with the PersonName
property of the component.
 When the user enters a value in the text box, the same will be automatically
updated in the PersonName property of the component.
 The meta data is additional details about the specific class; here, components,
directives, modules and services are the classes.
 That means all of these components, directives, modules and services contain
it's own meta data.
 Modules that mainly used to a group-up the related components.
 In general, every project module is created as a angular module.
 Service is a typescript class which contains client side business logic which is
involved in loading the data from servers by making AJAX calls to the REST
API servers, and also process the received data, by performing custom and
complex validations and calculations and also adding additional essential data
to the data structures.
 Dependency Injection is a concept of creating service objects at runtime
automatically and loading those service objects into the constructor of the
components as per the necessity of the component.
 In general, directives are mainly used it to create custom gadgets, such as a
draggable, modal popup, collapsible, accordion etc.
 This is all about angular architecture.

Angular Packages
1. @angular/core
• Provides essential pre-defined decorators, classes, interfaces and modules that are
needed to run every angular application.
• Ex: @Component, @NgModule, @Pipe,@Directive, @Injectable, @Inject, NgZone,
OnChanges,OnInit, Application Module etc.

2.@angular/common
 Provides built-in directives that are useful for most of the real-time applications.
• Ex:nglf, ngSwitch, ngClass, ngFor etc.

3.@angular/compiler
• Compiles "templates" (html code) into "javascript code".

4.@angular/platform-browser-dynamic
• Invokes the angular compiler (JIT compilation) and specifies hathe startup module
and also start executing the application.

5.@angular/platform-browser
• Provides a set of pre-defined classes that are related to DOM and browser
interaction.
• Ex:BrowserModule.

6.@angular/forms
Provides necessary pre-defined classes that are related to are needed to create and
execute angular forms.
• Ex: FormsModule, ReactiveFormsModule, Validators,ngModel, ngForm etc.

7.@angular/router
• Provides necessary pre-defined classes that are needed to create and execute
angular routes.
Ex: RouterModule, Routes, Activated Route, CanActivate, routerlink etc.

8.@angular/animations
• Provides necessary pre-defined classes that are needed to create and execute
angular animations.
• Ex:BrowserAnimations Module, animate,state, style,transition etc.

9.@angular/cli
Provides necessary pre-defined commands that are needed to create, compile, build,
add items in angular applications.
Ex:ng new,ng serve, ng build, ng test etc.

10. rxjs
Provides necessary pre-defined classes for creating Observables, which are needed
to represent the response of REST-API calls of AJAX.
.Ex:Observable,Observer, Subject etc.

11. zone.js
Provides necessary pre-defined classes for executing "change detection processes",
while executing angular app.

Angular App Folder Structure


• e2e Contains "end-to-end" test cases.

 src Contains source code of the application.


 app
.app.component.scss : Contains CSS styles of AppComponent.
.app.component.html : Contains template of AppComponent.
.app.component.spec.ts : Contains unit test cases of AppComponent.
.app.component.ts : Contains AppComponent.
.app.module.ts : Contains AppModule.
app-routing.module.ts : Contains Routing Configuration.
• assets : Contains static files such as images.

 favicon.ico : Contains browser icon.


 index.html : Default page/startup page.
 main.ts : Defines Startup Module.
 polyfills.ts : Defines polyfills(additional scripts) needed to load& run app.
 styles.scss : Contains global CSS styles of entire app.
 angular.json Contains Angular CLI configuration.
 Package.ison Defines current and (package) details and its dependencies.
 tsconfig.json Contains TypeScript Compiler configuration settings.

Flow of Execution od Angular App


The most important flow of execution of Angular app is:
First, the execution flow beings with index.html. That means, the browser loads
index.html file into the memory.
And as per the tags of the index.html, the main.ts file will be invoked.
That means, the compiled version of main.ts will be invoked; not the actual file.
And from there, we are navigating to AppModule.
And that AppModule definition is present in the file called app.module.ts.
And from there, it moves to AppComponent.
AppComponent has AppTemplate also.
So app.component.ts and app.component.html file; both work together as a single
unit.
This is the very fundamental flow of execution of Angular application.
So the main.ts file invokes the AppModule. And AppModule invokes AppComponent.
And main.ts invokes AppModule by adding a statement called
"bootstrapModule(AppModule)".

Adding Bootstrap in angular project – npm install jquery –save


- npm install popper.js –save
- npm install bootstrap –save
Then in angular.json file add node_modules/bootstrap/dist/css/bootstrap.css – in
styles
And in scripts -- node_modules/bootstrap/dist/css/bootstrap.js

WHAT IS COMPONENTS
Component is a class that contain "application data + even handler methods".
For every screen, you require to create a component.
For example for a dashboard page you require to create a dashboard component.
Component contains application data in the form of properties or arrays, that is
required to display the view.
And also it contains even handler methods, in order to respond to user actions.
For example in the "myprofile" page, I want to display the name of the person.
So person name is the property that is available in the component class.
And when the user clicks on the save button, it is going to execute a method called
"onSaveClick", which is present inside the component class.
Every component is associated to a template.
In other words, one component has only one template.
Template contains design logic that is HTML logic.
Template can access all the properties and event handler methods of the
corresponding component.
For example the text box binds to "personName" property of the component.
The button binds to "onButtonClick" method of the component.
A component can call other component through its template.
That means in the template of one component, you can call another component.
Component's additional details are called metadata of the component.

What is routing?
"Angular Routing" is an integral part of Angular, which allows us to load components
based on the URL changes in the browser's location bar.
So the user experiences the page navigation using single page application technique.
Here Single page application is a technique, which allows us, to navigate among
screens only within the client side itself, instead of reloading the full page.
A Route maps an URL to a component.
For example the URL dashboard, maps to dashboard component.
So when another user enters the URL "dashboard", it automatically loads the
dashboard component.
1 Define Base URL in "index.html"file

<base href="/">

2 Create hyperlink for route


<a routerLink="/path"> Link text </a>

Property '…' has no initializer and is not definitely


assigned in the constructor
In case if you get above error, add the following property in tsconfig.json,
which is present at root folder of your application:
1. "strictPropertyInitialization": false

Data Bindings

• Relationship between "Template's HTML Element" and "Component's Property".


• The value of "Template's HTML Element" will be automatically updated into
"Component's Property" and vice versa.
Interpolation Binding
Component Template
{{ }}
Property HTML Element
Property Binding
Component Template
[]
Property HTML Element

Event Binding
Component Template
()
Property HTML Element

Two-Way Binding
Component Template
[( )]
Property HTML Element

Style Handling
• [style.property] = "value"
• [style.property] = "(condition)? truevalue : falsevalue"
• [ngClass] = "value"
• [ngClass] = "(condition)?truevalue:falsevalue"

Built-in Pipes

Component Template

Pipe

Property HTML Element

{{property | uppercase}} Converts string to upper case.

{{property | lowercase}} Converts the string to lower case.

{{property | slice: startIndex:endIndex}} Gets part of string, between startindex


and endindex.

{{property | number:.2 }} Provides digit grouping and controls decimal places.

{{property | currency:"USD"}} Providers currency symbol.

{{property| percent}} Converts the number to percent.

{{property| json }} Converts the"JavaScript object"to "json"

{{property| date}} Specifies date format.

ngSwitch

<tag[ngSwitch]="property">

<tag *ngSwitchCase=" 'value1"">Content here</tag>

<tag *ngSwitchCase=" 'value2""> Content here</tag>


<tag *ngSwitchCase=" 'value3"">Content here</tag>

<tag *ngSwitchDefault>Content here</tag>

</tag>

What is Angular's Module?


•Module is a collection of Components, directives, pipes.

•Mainly used to organize the components and others (directives and pipes).

Goals of Modules:

• Consolidate components, directives, pipes into cohesive of functionality.

• Make some of the components, directives, pipes public; so that, other module's
component templates can use them.

•Import components, directives, pipes from other modules, that are required by
current module's component templates.

•Provide services that the other modules can use.

Module Definition and Metadata


•Angular Modules are called NgModules.

•An NgModule is a class that is decorated with "NgModule" decorator, that contains
the following metadata;

Module metadata:

• declarations: List of components, directives and pipes, that are part of current
module.

•exports: List of components, directives, and pipes, that are public, that can be
accessible in other modules, that are importing the current module.

•imports: List of modules, that the current module imports; so, the current module
can use components, directive, pipes that are already exported by that particular
module.

• providers: List of services that can be used by the components, directives and
pipes of current module.

What is Service in Angular?


• Service is a class, which is a collection of properties & methods, which
contains re-usable programming logic, which mainly contains "business logic" and
also performs "data source interaction".

• Services can be accessible in components.


Goals of Services:

• To separate business logic and data access logic from components.

▪ Make components contain code for only supplying the data to the template and
respond to the user actions such as click and also call the necessary services.

Steps to work with Angular Services

1. Create Service class:

• Create a class with one or more properties and methods that contains business
logic and data access logic.

2. Make ready the Service for Dependency Injection:

Add @Injectable()decorator above the service class.

3. Provide the service Globally/Locally:

• Add provided in: "root" option in @Injectable( )decorator. [or].

• Add providers:[Service ] in AppModule's metadata. [or].

• Add providers: [ Service ] in any other module's metadata. [or].

• Add providers: [ Service ] in any other component's metadata.

4. Inject the service into actual component:

• Add @Inject(Service) private referenceVariable :Service in any component's


constructor. [or] (@Inject(service) is not compulsory)

• Add private reference

ariable : Service in any component

What is Observable and Observer?


."Observables and Observer" is a pattern of "message passing" from "publisher"to

"subscriber".

Flow of functionality:

• Observable is created.

• Observer subscribes to the Observable.

• Observable can pass messages (notifications) to the Observer.


• Each time, when the Observable passes a notification, it is received by
Observer. (One observable can have one or more observers.The subscriber class can
create multiple observers from different observables.)

Real-time usage of Observables and Observer:

▪ While receiving response from AJAX.

▪ While performing large tasks in client(browser).

▪ Observables execute only when the observer subscribes to it.


There is an observable object.
It won't execute until the observer is created for that.
Now the observer subscribes to the observable. The observer has three functions:
HandleData, HandleError, and HandleCompletion.
The HandleData function executes each time when the observable sends some
notification or data to the observer.
It is able to receive and print the data, sent by the observable.
For example, some data is received from server after sending AJAX request.
The HandleError function executes only once, in case of any run time error occurs
while executing the observable.
For example the observable raises an error while executing AJAX request.
The HandleCompletion function executes only once in case of successfully process
is completed.
This is the introduction to observables and observers.

What is AJAX?
• AJAX(Asynchronous JavaScript And Xml) is NOT a language, but it is a
concept,which is used to"send background request to server" and also "get
background response from server",without refreshing (reloading) the web page in
the browser.

Browser(Client)
Server
• User performs some activity
Receive the request from browser
Send AJAX request to server
• Do process(db connection)
Same Browser(Client)

Get response from server
Send response to browser
Display the response

Types of Requests

• Get : Used to retrieve/search data from server

• Post : Used to insert data to server

• Put : Used to update data on server

• Delete : Used to delete data from server

RXJS Map

The "Map"is an RXJS Operator,which executes a function after receiving response


from the server.
Server  Send Response  Map [Business logic& modify the response]  subscribe
 Handle Data [Receive modified response]

pipe(map(

(data) =>

//do all changes here and then return data

return data;

))

Learn more about rxjs

JWT Authentication
• A JSON Web Token (JWT) is a JSON object that is defined in RFC 7519 as a safe
way to represent a set of information between two parties.

• RFC(Request For Comments)is a formal document released by IETF (Internet


Engineering Task Force),who releases Internet Standards.

How JWT Authentication Works?

The most common scenario of JWT is authentication.

.Once the user logs-in, JWT(an encrypted token) will be sent to the client;

• Each subsequent request includes JWT sent to the server;then the server
validates JWT and provides response only when the JWT token is valid.

.The signature is generated based on the header and payload; so that receiver can
verify the content hasn't been tampered with.

Template driven Forms


● Suitable for simple forms with less no. of fields.

● Implemented based on Forms Module.

● ngModel is used for binding.

● Validation rules are written in the component's template.

● Validation messages are defined and displayed in the component's template.

• Not unit testable.

● Example: Login form, Search form.

<input type="text" [(ngModel)]="personName">

Validations in Template Driven Forms

• required attribute

 Specifies that the field is mandatory (can't be blank).


• pattern attribute

 Specifies regular expression.

• minlength attribute

 Minimum no.of characters to accept.

• maxlength attribute

 Maximum no.of characters to accept.

Validation Properties in Template Driven Forms

• untouched property

true: The field is not focused at least once.

false: The field is focused at least once.

• touched property

true: The field is focused at least once.

false: The field is not focused at least once.

• prestine property

true: The field is not modified at least once.

false: The field is modified at least once.

• dirty property

true: The field is modified at least once.

false: The field is not modified at least once.

• valid property

true: The field is valid (has no errors).

false: The field is invalid(has errors).

• invalid property

true: The field is invalid (has errors).

False: The field is valid (has no errors).

• errors property

required: The field is invalid because of "required" rule.

pattern: The field is invalid because of "pattern" rule.

minlength: The field is invalid because of "minlength" rule.

maxlength: The field is invalid because of "maxlength" rule.

Ex :- <div class="form-group row">

<label for="txtNewProjectID" class="col-sm-4 col-form-label">Project ID</label>

<div class="col-sm-8">
<input type="text"id="txtNewProjectID"style="width:130px"class="form-
control"placeholder="Project

ID"name="ProjectID" [(ngModel)]="newProject.projectID"
required="required"pattern="^[0-9]*$"

#newProjectID="ngModel"[ngClass]="{"is-invalid":newProjectID.invalid
&&(newProjectID.dirty ||

newProject.touched || newForm.submitted), 'is-valid': newProjectID.valid &&


(newProjectID.dirty ||

newProject.touched || newForm.submitted)}">

<span class="text-danger"*ngIf="newProjectID.invalid &&(newProjectID.dirty ||


newProjectID.touched ||

newForm.submitted) && newProjectID.errors?.required">Project ID can't be


blank</span>

<span class="text-danger"*ngIf="newProjectID.invalid &&(newProjectID.dirty ||


newProjectID.touched ||

newForm.submitted) && newProjectID.errors?.pattern">Project ID should contain


numbers only</span>

errors? - we are using "?", which indicates that read the right side property i.e. "required"
only when the "errors" property is != null.

Reactive Forms
• Suitable for simple/complex forms with any no. of fields.

• Implemented based on Reactive FormsModule.

• formGroup and formControlName is used for binding.

• Validation rules are written in the component.

• Validation messages are defined and displayed in the template.

• Unit testable.

• Each form element is represented as "FormControl";

• Group of form controls is represented as "FormGroup".

<form [formGroup]="myForm">

<input type="text"formControlName="personName">

</form>

SET VALUE, PATCH VALUE, RESET VALUE IN REACTIVE FORMS

this.myForm.setValue( { property: value } );

● Overwrites all the form elements in the form group.

• You must pass values for all form elements.

this.myForm.patchValue( { property: value } );

● Updates specific form elements in the form group.


• You can pass only specific form elements.

1 ths.myForm.reset();

• Clears the values of all form elements.

2 ths.myForm.reset( { property: value } );

• Clears the values of all form elements.

• And also updates the specified form elements.

Form Array in Reactive Forms

• Represents an array inside the Form Group.

• You can add FormControl, FormGroup or another FormArray, inside the FormArray.

myArray:new FormArray( []);

Form Builder in Reactive Forms

• Meant for simplifying the syntax of creation of FormGroup, FormControl and


FormArray.

FormGroup: this.form Builder.group( {} )

FormControl: this.form Builder.control( defaultValue )

FormArray: this.form Builder.array( [] )

Validation in Reactive Forms


• Validators.required function

Specifies that the field is mandatory (can't be blank).

• Validators.pattern function

Specifies regular expression.

• Validators.minlength function

Minimum no. of characters to accept.

• Validators.maxlength function

Maximum no.of characters to accept.

● Validators.min function

Minimum value for numerical field

● Validators.max function

Maximum value for numerical field.

● Validators.email function

Performs email validation

Custom Validations in Reactive Forms


Define a function of type ValidatorFn, that contains validation logic.

export interface ValidatorFn


{

(control:AbstractControl): ValidationErrors | null;

public static myValidator(parameter: dataType): ValidatorFn

return (control: AbstractControl): ValidationErrors | null=>

if(condition)

return null;// valid

else

return {'errorName': { valid: false }};

};

Parent to Child communication using Input Binding


• An Input Property is a settable property, annotated with an @Input()decorator.

class ChildComponent

@Input("someInputName"): propertyName:dataType;

<app-child [someInputName]="valueOfParent"> </app-child>

Parent to Child using ViewChild


• ViewChild decorator refers to single instance of element/component in the
template.

class ParentComponent

@ViewChild("referenceVariableName"): variableName : ChildComponent;

<app-child #referenceVariableName> </app-child>

//If we want to access any child component method from parents component.

• ViewChildren decorator refers to multiple instances of elements /components in


the

template.

class ParentComponent

{
@ViewChildren("referenceVariable"): variableName :QueryList<ChildComponent>;

<app-child #referenceVariable> </app-child>

Custom Event using Output Binding (Child to


Parents)
• An Output Property is an observable property, annotated with an @Output()
decorator.

class ChildComponent

@Output("someOutputName"): eventName : EventEmitter = new EventEmitter();

eventName(event) {

this.someOutputName.emit({event})

--parents component

<app-child(someOutputName)="methodName()"> </app-child>

//If we want to access any method of parent components from child component then
use output decorator

 Components can indirectly communicate through service

Custom RxJS Observables

• Observable passes notification to Observer.

• Create Observable in Service.

• Subscribe to the Observable in Component.

Observable.create((observer: Observer<dataType>) => {observer.next(data);

});

myObservable.subscribe((data)=>{

// do something with the data

});

RXJS - Subject

.Plain Observables unicast the values to observers.

.Subject class multicast the values to all observers at-a-time.

.Subject= Observable + Array of Observers

var mySubject= new Subject<dataType>();

subject.next(data);
mySubject.subscribe((data) => {

// do something with the data

});

Passing Content from Parent to Child (Sharing HTML Content)

1. Pass content,while invoking the child component, inside the parent


component's template.

2. Next, render the content, inside the child component's template, using <ng-
content>.

Template of Parent Component

<app-child>

<element1></element1>

<element2></element2>

</app-child>

Template of Child Component

<ng-content> </ng-content>

CONTENTCHILD

The child component can access the properties and methods of grandchildren that are
passed by the parent component, by using the ContentChild decorator.
1. ParentComponent supply some grand children elements, as "content", to the
ChildComponent.

2. ChildComponent renders those elements, using <ng-content>, in the


ChildComponent's template.

3. The ChildComponent can access the elements of Grand children, by using


"ContentChild".

The ContentChild represents only one instance of GrandChildComponent.

Parent Component's Template

<app-child>

<app-grand-child #referenceVariable> </app-grand-child>

</app-child>

Child Component

class ChildComponent

@ContentChild("referenceVariable"): variableName : GrandChildComponent:

Custom Pipe
.Pipe class is decorated with @Pipe decorator.

.Pipe class implements PipeTransform interface that contains transform method.

@Pipe({

name: 'pipeName'

})

export class PipeClassName implements Pipe Transform

transform(value: any, args ?: any):any

return yourTransformedValue;

PURE PIPES VS INPURE PIPES

Pure Pipe

@Pipe({

name:'pipeName'

})

• Assume,the pipe receives an object as "value".

• Pure pipe doesn't re-executes, in case of any changes to the object properties.

• Assume,the pipe receives an array as "value".

• Pure pipe doesn't re-executes, in case of any elements added to removed in the
array.

Inpure Pipe

@Pipe({

name:'pipeName',

pure:false

})

Assume,the pipe receives an object as "value".

• Pure pipe re-executes automatically,in case ofany changes to the object


properties.

• Assume,the pipe receives Veb University an array as "value".

• Pure pipe re-executes automatically,in case of any elements added of removed in


the array.

Interview Question

What is difference between constructor and ngOnInit?


The constructor() should only be used to initialize class members but
shouldn't do actual "work". So we should use constructor() to setup Dependency
Injection, Initialization of class fields etc. ngOnInit() is a better place to write "actual
work code" that we need to execute as soon as the class is instantiated.

You might also like