Angular — Fast Development Reference

Angular In Depth part-1 (Intro, Installation, Component basics, Data binding, Event Binding, Angular Directives)

Syed Khizaruddin
Frontend Weekly
10 min readDec 27, 2019

--

Angular Coding, blue screen, mug, quotes
Photo by Tudor Baciu on Unsplash

Pre-requisites:

  1. JavaScript knowledge.
  2. Typescript knowledge.
  3. Html CSS basics.
  4. Computer or Laptop (MacOS ).
  5. Internet.

Angular Basics:

Introduction:

Angular is a framework which allows to create SPA Single Page Applications.

The entire project build on angular framework is shrunk into one html and several JavaScript files at time of compiling it to production mode. Hence only one page i.e. index.html is used to serve the entire project and only what user want to see just that thing is loaded by JavaScript.

It gives experience of using a desktop application in web browser.

Angular versions:

Latest version at the point of writing this post was angular 8.

  1. AngularJS was first version.
  2. Angular 2 was complete re-written of AngularJS.
  3. So angular 2 till angular 8 is the same with some incremental updates or new features.

Installation of NodeJS:

You need to install NodeJS from https://nodejs.org/en/download/ after installation.

To check version of node, run:

node -v

To check npm version, run:

npm -v

If permission error occurs use

sudo node -v

or

sudo npm -v

sudo is applicable to all terminal commands in this post if you get permission error.

pouring milk in tea
Photo by Alex Boyd on Unsplash

Angular Installation:

Open terminal and run,

npm i -g @angular/cli

Make sure angular is installed to crosscheck run ng v you will get angular version if not your installation had some error so reinstall it.

To create new angular project use ng new project-name

How angular application works?

When we visit localhost:4200 which is hosted by Angular CLI we see our application.

The angular server only serves index.html from angular project which is only one page hence called Single Page Application.

It has app-root tag consisting of “Loading…” as a text inside of it. The only selector wrapped inside body tag is app-root tag.

So we can see the loading is changed with some other file and that is due to components.

We have app component created by default on creation of Angular project by Angular CLI.

Number of Components makes up a module, We need to register component inside of a module declarations.

App-root is a component tag to call app component from our app component folder.

This component folder has those 3 files (app.component.html, app.component.ts, app.component.css). The app.component.ts is responsible to bind app-root with these html css and TS files.

It is done by using component decorators.

It has selector property inside object given to component decorator.

So inside app.component.ts file we have.

import { Component } from "@angular/core";@Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: [      './app.component.css'   ];})export class AppComponent {}

So app-root is replaced with what we write inside app.component.html and styles inside app.component.css and logic from app.component.ts file.

If we debug in our browser we see there are some scripts injected in index.html these scripts are injected by angular cli in compilation time,

The first code which is executed is main.ts file, so here we check if we are in production mode or in development mode, bootstrapModule is used to start our angular project so it gets AppModule as an argument which is our root module.

This AppModule binds all other components and other modules. In AppModule TS file there is a bootstrap inside @NgModule() decorator because of which, on angular serves the project, it opens AppComponent class from app.component.ts file which in turns invokes component’s HTML and CSS contents.

A Module is a container that has numbers of component. It is important to register a new component in a module.

That’s why the app-root is replaced by app.component.html with TS logic and styles written inside CSS and TS file.

COMPONENT:

Components are key feature in Angular with which we can create our whole application.

Each element can be a component it can be navbar, single nav items, nav container, sidebar header, main content, product-list, product-list-item, product-detail, aside, sidebar, footer, gallery, cart, shop, right-sidebar, and can be anything.

We can re-use components in our website. Component consists of html css and particular logic of that component.

Components created must be registered in ‘@NgModule’ decorator’s declarations array.

Component.ts file looks like this below:

import { Component } from "@angular/core";@Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: [      './app.component.css'   ];})export class AppComponent {}

Good naming convention is to use component-name.component.html, component-name.component.css, component-name.component.ts.

for example: navbar.component.html, navbar.component.css, navbar.component.ts, app.module.ts, truncate.pipe.ts, api.service.ts, db.model.ts, app-routing.module.ts, select.directive.ts and many more.

selector’ inside ‘@Component’ decorator is used to select an html tag or html attribute or a class so that, selected element gets replaced with the the components component.html file.

We can call this component anywhere in our website by using this selector name.

Selector is just like css selector. We cannot select element by id, or hover or pseudo selectors it is not supported by angular.

The ‘templateUrl’ inside ‘@Component’ decorator is for binding TS with HTML file and ‘styleUrls’ is for binding number of component css files.

We can also write HTML inside component.ts file inside ‘@Component’ Decorator like below:

@Component({   selector: 'app-root',   template: `     <div>       <h1>heading</h1>     </div>   `,   styleUrls: [      './app.component.css'   ]})
export class AppComponent {}

We can also write styles inside ‘@Component’ decorator,

@Component({   selector: 'app-root',   template: `      <div>        <h1>heading</h1>      </div>   `,   styles: [ `     .h1{       color: red;     }   `]})export class AppComponent {}

We need to use only one approach in both of the case i.e. html and css.

The template either of them is necessary field we cannot skip it, though selector and styles can be removed.

[ Note: template and templateUrl takes string value and ‘styles’ and ‘styleUrls’ takes array of string values ]

If we create component from scratch we have to register it inside a module or root module if we don’t have multiple modules.

All components are declared inside declarations array inside ‘@NgModule’ decorator of app.module.ts.

If we do it with cli we don’t need to declare it inside ‘@NgModule’ Decorator cli does it for us.

To use angular cli to create new component we use:

> ng generate component component-name

or for short syntax,

> ng g c component-name

How to add bootstrap or any npm package in our project:

Simply by using

ng add bootstrap@3.3.7

or for latest version we use:

ng add bootstrap 

or ,

ng add bootstrap@latest

We can install it from npm as well

For other npm packages we use

npm i -D packageName 

[note: -D is used to update package.json file as a dev dependency -S for project dependency]

Photo by PAUL SMITH on Unsplash

DATA BINDING:

Data binding is used to output data which is little dynamic. Data binding is the communication between TS logic and html.

To output data from TS to html we use String Interpolation to update data from html to TS we use Property Binding if we want to react to user events we use Event Binding, for two way communication i.e. output data and update TS file at same time we use Two-way Binding.

String Interpolation:

In TS file of component we can create class variable and that class variable can be used inside html file. Through string interpolation we can show the content of that variable.

TS file:

// … decorators and imports above…export class AppComponent{   myName: string = 'khizar';   getName(){     return this.myName;   }}

Html file:

<div>   <h1> {{ myName }}</h1>   <h1> {{ myName == 'khizar' ? 'hi' : 'hey' }}</h1>   <h1> {{ getName() }}</h1></div>

We can write any expression inside string interpolation that eventually gives out string. So, what if we have to give number? The string interpolation converts number into string and thus we can use it.

Property Binding:

We can bind data with property of an html like for example binding boolean value with disabled property of a button, and changing that value programmatically to disable or enable a button.

TS file:

// … decorator and imports above…export class AppComponent{   isDisabled: boolean = false;   constructor() {      setTimeout(()=>{        this.isDisabled = true;      }, 3000);    }    myName: string = 'khizar';    getName(){       return this.myName;    }    toggleDisable(){       this.isDisabled = !this.isDisabled;    }}

Html file:

<button [disabled]="isDisabled">   {{ `isDisabled : ${isDisabled}` }}</button>

This button will be enabled automatically after 3seconds.

Event Binding:

If we need to bind any browser event like click mouseleave, mouseenter, keyup, keypress, keydown, hover, input, etc. we write event name enclosed in between parenthesis on the html tag we want to fire event on.

Example,

Html:

<button type="button" (click)="onClickFunc()" > click me </button>

TS:

export class AppComponent {   constructor() {}   onClickFunc () {      console.log(" hey I'm clicked");   }}

We can call a function on firing event or assign a value or calculate an expression as well but should not be complex calculation just one line.

Passing data from input to TS file:

Html:

<input type="text" (input)="updateData($event)" />

TS:

export class AppComponent {   data;   constructor() {}   updateData($event) {      this.data = (event.target as HTMLInputElement).value;   }}

Here we are firing input event which passes event object to updateData function every-time the input string is entered.

Here in TS file we have explicitly used type casting to make TS know that the event.target will be of type ‘HTMLInputElement’

In angular the data flows from TS file to html file.

So when html is updated we need to fire some event so that data is passed through that event and update the TS.

There is another way of binding data which is called two-way data binding

For this to activate we need to make sure we have imported FormsModule in our parent module holding the component for now let’s say app.module.ts

app.module.ts

@NgModule({   declarations: [      AppComponent,   ],   imports: [     ...     FormsModule,   ]}export class AppModule { }

Note: if we don’t import it, In browser console we will see errors

Now we can use ‘[(ngModel)]’ inside html file.

Html:

<input type="text" [(ngModel)]="data" (change)="updateData()" />

TS:

export class AppComponent {   data: Event;   constructor() {}   updateData($event) {     console.log(this.data);   }}
Photo by Austin Distel on Unsplash

Directives:

Directives are instructions in the dom.

Components are such instructions in the dom.

How?

By using app selector of a particular component say ‘<app-component></app-component>’ in template we are saying that all the html template and business logic of that component must be replaced at the place where we used the app-selector.

Components are directives with templates There are directives without templates as well

For example:

Html:

<p appTurnGreen> this text is green </p>

turn-green.directive.ts:

@Directive({   selector: "[appTurnGreen]"})export class AppTurnGreenDirective { }

Here where-ever we place appTurnGreen in our project the value of that tag will get replaced with what we logic we implement inside our directive.ts file. We can add text remove text delete text strip our text or add class remove class or can do all the things which is possible to do with an html tag.

There are two types of directives:

  1. Attribute directives.
  2. Structural directives.

Structural directives:

These directives when used changes the structure of the dom.

They are directives with ‘*’ appended before the name for example *ngIf, *ngFor etc.

ngIf:

It takes condition which returns a Boolean value or a variable containing a Boolean value. So it works as like if statement in programming. So if the condition or a variable is true the html element where it is used, is added in html Dom and if the condition or the variable used is false the html element where it is used will not be added in html dom.

Html syntax:

<p *ngIf="condition"> 
This will be appended only when condition is true
</p>

Or

<p *ngIf="isStatus"> 
this will be appended only when isStatus is true or becomes true
otherwise it will not be appended in the HTML DOM
</p>

TS file:

export class AppComponent {   constructor() { }   isStatus: boolean = false;   onCreate() {     this.isStatus = true;     ...   }}

We have else part as well with ‘ngIf’

As below:

<p *ngIf="isServerCreated; else noServer" > server created if isServerCreated is true else it will show noServer block</p><ng-template #noServer>   <p> this will be appended when else part is run</p></ng-template>

So here when if block is false it will go to else part and ‘noServer’ which is ‘HTMLReference’ we have created on ‘ng-template’ tag will be seen

ngFor:

This directive is used to output list of elements or to iterate number of html elements.

It is used as below:

Html:

<ul>   <li *ngFor="let item of items; let i = index">      {{ i +1 }}. {{ item }}   </li></ul>

// let i = index, is used to get iteration count value. i.e index

values of the array.

TS:

export class AppComponent {   constructor() { }   items: string[]=["sugar", "banana", "apple", "mango"];   ...}

Attribute directives:

These are directives which does not add or remove or change html dom. They just change the element they are placed on.

These directives does not need ‘*’ at the beginning.

For example: ngStyle, ngClass

NgStyle:

It is used to style the element dynamically.

It needs property binding to work.

Html:

<p [ngStyle]="{ backgroundColor: 'red' }">
this html tag has background color red
</p>

So ‘ngStyle’ takes javascript object having key and value pairs of style we want to apply on that tag

The keys inside object can be used as, we use in CSS, by enclosing it with single quotes as below or we can use ‘camelCase’ as above.

Html:

<p [ngStyle]="{ 'background-color': 'red' }"> 
this html tag has background color red
</p>

We can also call a method inside the object

Html:

<p [ngStyle]="{ backgroundColor: getColor() }"> 
this html tag has background color red
</p>

NgClass:

NgClass is another attribute directives that is used to add class dynamically. It needs property binding to work.

Html:

<p [ngClass]="online: serverStatus === 'online'"> I'm online</p>

CSS:

.online{   color: green;}

The class online will be added only when ‘serverStatus’ becomes online.

we can also use ternary operator inside ngClass as below:

Html:

<p [ngClass]="serverStatus ? 'online' : '' "> I'm online</p>

here we are checking if ‘serverStatus’ is true or not if it is true we will add online else we will leave it empty.

a yellow sign having TO BE CONTINUED… written
Photo by Reuben Juarez on Unsplash

In next post, we deep dive into components and data-bindings.

TLDR;

Please follow for more content.

Do give a clap if it’s worth it.

Follow me on Twitter: here.

Buy me a coffee: here

Other topics covered by me:

  1. Typescript — Fast Development Reference: link.
  2. JQuery — Fast Development Reference: link.
  3. SQL Mastery — Fast Development Reference: link.

--

--