DEV Community

Varun
Varun

Posted on

Angular Crash Course in One Shot🚀🔥

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

  1. Confirm the navigation operation
  2. allow access to certain parts of application to specific users.
  3. validating certain parameters before navigating to the root.
  4. fetch data before showing component view

Types of Route Guards:

CanActivate:
CanDeactivate:
Resolve:
CanLoad:
CanActivateChild:

Process:

  1. Create a route guard as service
  2. The Service class should implement route guard interface.
  3. Take interface and provide the method inside the service class
  4. from this method we need to return True or False.
  5. 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}

        }
}
Enter fullscreen mode Exit fullscreen mode
  1. Use route guard on the route which required to be guard in routers

eg. {path: 'stuff', component: BuyStuffComponent, canActivate: [StufffRouteService] }

DATA BINDING

  1. 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>`
Enter fullscreen mode Exit fullscreen mode
  1. Property Binding:
    one way data binding, sets property for HTML elements
    updating property value in component for HTML element

    eg. public image = "/assets/Logo.png"

  2. 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 component

    eg. Subscribe

  3. 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}}

Enter fullscreen mode Exit fullscreen mode
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.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Decorators:

design pattern that define how an angular feature works. They make 
prior modifications to class, service.
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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'}

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Angular Directives:

First Of all Angular has 3 type of Directives

  1. Structural Directives
  2. Component Directives
  3. Attribute Directives

1. Structural Directives:

1. NgIf
2. NgFor
3. NgSwitch
Enter fullscreen mode Exit fullscreen mode

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

  1. HTML template that declared what need to be rendered on the page
  2. a typescript class which defines the behaviour of elements and methods
  3. CSS selector which defines how the component is used in the template
  4. and optionally, css styles are used on the template.

3. Attribute Directives:

These Directives changes appearances of elements, comoponents and other Directives.

  1. NgClass - adds and removes set of css classes
  2. NgStyle - adds and removes HTML styles
  3. ngModel - adds two way databiding to HTML form element

so these Directives listen and modify behaviour of HTML elements, Attributes and properties.

  1. 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,
       };
}   
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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'
    };
}
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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">
Enter fullscreen mode Exit fullscreen mode

That's all for Now🌱. Hope this helps in your Web Dev Journey, Happy Learning 🚀!!

Top comments (2)

Collapse
 
shagwell profile image
Ezra Erewharighe

This is beauutiful

Collapse
 
raddevus profile image
raddevus

This is a very nice article with a lot of great content.

I would just like to see a Stackblitz project associated with it so I could see live code with the examples incorporated. That would help to make this fantastic article even better.

Do You Know Stackblitz?

Do you know Stackblitz? It's a web-based IDE where you can create all sorts of projects (React, Bootstrap, etc. and including Angular of course).
Check it out at: stackblitz.com/
It's FREE and there are templates for generating basic projects based on all the technologies. Also, after you create the project remotely you can download it locally and run it very easily. Really cool!
Hey, would you mind taking a look at my most recent article here on dev.to, Software Developer, Are You Just a Hammer?