Angular Crash Course in One Shot🚀🔥
Varun
Posted on July 31, 2023
Hi Guys👋, Today We will go through Angular for an Experienced DEV. This will be useful to go through after learning everything or if you are preparing for an Interview. So lets Start 🚀🔥
Components in ANGULAR Folder :
package.json:
It contains basic info about project.
Required for every project
records imp metadata about project, such as name, description, script, dependencies.
package.lock.json:
automatically generates for operations with chanage in node_modules
allows to install same dependencies for future devs
contains name, dependencies, locked version of the project
ROUTE GUARD:
Angular route guards can be used to control whether the user can navigate to or away from the given route based on some condition.
Used to secure route or perform some operation before navigating to a route or leaving the route.
e.g where can we use the route guards?
suppose we are using the application to buy some stuff, but we havent logged in. Now when a user clicks on buy button, he should be redirected to checkout page only if
he is a logged in. otherwise first he should be sent to login, and then only to checout page., so here route guard is helpful
route gaurd can also be used to
- Confirm the navigation operation
- allow access to certain parts of application to specific users.
- validating certain parameters before navigating to the root.
- fetch data before showing component view
Types of Route Guards:
CanActivate:
CanDeactivate:
Resolve:
CanLoad:
CanActivateChild:
Process:
- Create a route guard as service
- The Service class should implement route guard interface.
- Take interface and provide the method inside the service class
- from this method we need to return True or False.
- if true navigation process will continue else it will stop.
cmd: ng g g guardname
@Injectable()
export class StuffRouteService implements CanActivate{
// this is service class which implements CanActivate Interface
// and below is method to be provided
canActivate()
{
//check if route can be activated
if (condition)
{ return true;}
else { return false}
}
}
- Use route guard on the route which required to be guard in routers
eg. {path: 'stuff', component: BuyStuffComponent, canActivate: [StufffRouteService] }
DATA BINDING
- Interpolation Binding: data is being taken from compoenent to HTML view. Allows user to bind values to user interface
comoponent:
public data= "this is the req data"
HTML:
`<h1>{{data}}<\h1>`
-
Property Binding:
one way data binding, sets property for HTML elements
updating property value in component for HTML elementeg. public image = "/assets/Logo.png"
-
Event Binding:
one way data binding, opposite of property binding
when user clicks a button, event bind to it inform of method
in component gets a call.
so data flows from view to componenteg. Subscribe
Two Way Binding:
data flows from compoenent to view and back.
this binding ensures changes made in app, gets reflected
immediately on both ends. general syntax: [()]
component:
public data= ""
HTML:
<input [(ngModel)]="data" type="text"]>
{{data}}
so here data is defined in .ts file and input is taken and it is
stored as data, and again data is interpolated in view.
Single Page Applications:
applications which loads only once and to display new features,
new page does not need to be loaded completely, instead with the
DOM manipulation of JS, content is generated dynamically, on the
existing page itself.
Decorators:
design pattern that define how an angular feature works. They make
prior modifications to class, service.
Class Decorators:
this tells to angular if perticular class is component or module.
eg @Component and @NgModule
Property Decorators:
allows to decorate some properties within our classes
eg: @Input, @Output, @Override
for @Input angular compiler will create an input binding with the
property name and link it
Method Decorators:
Method decorators are used to decorate the method defined in class with functionality, eg: @HostListener
Parameter Decorators:
Applied to constructor parameter of the class and
used generally to inject a provider in constructor.
eg.
export class ParameterExample{
constructor(@Inject(ExampleService) exampServ)
console.log(exampServ);}
Dependency injection:
Components dependent on other components can be easily worked around using this feature.
Angular Forms:
to build angular forms, import forms module
and create a form in HTML and define #formID = "ngForm" and create a submit event (ngSubmit)="getData()"
and define getData method in .ts file.
and at the end make a register button.
SO this is basic structure of form.
Pipes:
pipes are used to transform values from one type to other
eg, we want to change lowercase to uppercase, change date format, change currency format etc
eg.
<h1>{{title | uppercase}}</h1>
<h1>{{today | date: 'fullDate'}}</h1>
now these operations can be made by creating functions and calling those here, but it takes times
so we use pipes to save time and make code simpler.
Slicing:
if title= 'ANGULAR TUTORIAL'
<h1>{{title | slice: 3: 6 }}</h1>
it will show, 'ULA'
JSON pipe:
user= {name: 'Raj'}
<h1>{{user | json}}</h1>
output will show: {name: 'Raj'}
Decimal Pipe:
<h1>{{2000.30 | number: 2.3-4}}</h1>
max digits will shown
before decimal 2 ie if there was 002000 it will remove first zeros
after decimal min 3 max 4
op 2000.300
currency pipe:
<h1>{{50 | currency: 'USD' }}</h1>
op: $50.00
Create Custom PIPE:
ng g p pipename
we can give arguments to custom Pipe, like we have given in currency.
html:
`<h1>{{50 | newpipe: 100 }}</h1>`
pipe file:
transform (value: number, ...args: number[]):
unknown{
let x = args;
return value* x[0]
//here in arguments we can also add multiple arguments
}
op: 5000
Angular Directives:
First Of all Angular has 3 type of Directives
- Structural Directives
- Component Directives
- Attribute Directives
1. Structural Directives:
1. NgIf
2. NgFor
3. NgSwitch
2. Component Directives:
These are most common and widely used Directives. components are like main builiding block of an angular project comoponents are used with templates, which consists of
- HTML template that declared what need to be rendered on the page
- a typescript class which defines the behaviour of elements and methods
- CSS selector which defines how the component is used in the template
- and optionally, css styles are used on the template.
3. Attribute Directives:
These Directives changes appearances of elements, comoponents and other Directives.
- NgClass - adds and removes set of css classes
- NgStyle - adds and removes HTML styles
- ngModel - adds two way databiding to HTML form element
so these Directives listen and modify behaviour of HTML elements, Attributes and properties.
- NgClass:
for single style we can use class binding
<h1 [style.background]="white"> element </h1>
otherwise for multiple styles to be added use a style class and assign it to NgClass
<h1 [ngClass]= "logged" ? 'loggedstyles' : '' > element </h1>
this will apply loggedstyles to h1 element if the user is logged in else nothing Applied
FOR METHODS:
in the comoponent file:
applyClasses= Record<string, boolean>= {}
setapplyClasses(){
// this will apply css classes based on the boolean values
// if the boolean value is True, class will be applied
// else if its False not applied
this.applyClasses= {
save: this.canSave,
update: !this.notChanged,
};
}
In HTML:
<div [ngClass]= "applyClasses"> save or update </div>
Note:
In example Angular applies classes on initialization and in case of changes. the example calls the setapplyClasses initially with ngOnInit(), and when properties changes.
- NgStyle:
With NgStyle we can define multiple inline styles simultaneously, with state of the component add method to component class
applyStyles= Record<string, boolean>= {}
setapplyStyles(){
// this will apply css style based on the boolean values
// if the boolean value is True, first style will be applied
// else if its False other style will be applied
this.applyStyles= {
'font-weight': this.canSave ? 'bold': 'normal',
'font-style': !this.logged ? 'italic' : 'normal'
};
}
In HTML:
<div [ngStyle]= "applyStyles"> Change Styles </div>
Note:
In example Angular applies styles on initialization and in case of changes, the example calls the setapplyStyles initially with ngOnInit(), and when properties changes.
- NgModel:
NgModel directive is used to disply a data property and update that property when the user makes changes.
first of all include FormsModule in app.module.ts
<label for="example">[(ngModel)]:</label>
<input [(ngModel)]="currentItem.name" id="example">
That's all for Now🌱. Hope this helps in your Web Dev Journey, Happy Learning 🚀!!
Posted on July 31, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.