Angular

Angular is a framework ( & NOT a library) for building client applications in HTML, CSS, and either JavaScript or a language like TypeScript that can be compiled (more accurately, transpiled) to JavaScript.

Angular 4 is the latest version of Angular. It is a TypeScript-based, front-end web application platform. Angular 4 is an improvement on Angular 2, but a total rewrite of AngularJS. It has a completely different architecture.

  • AngularJS is based on the model view controller, whereas Angular 2 is based on the components structure.
  • Angular 2 is a complete rewrite of Angular 1 or AngularJS, which was rewritten from scratch by the Angular team using Typescript version 1.8.
  • Angular 4 works on the same structure as Angular2 but is faster when compared to Angular2.
  • Angular 4 supports TypeScript 2.2 (which compiles to JavaScript and displays the same in the browser), whereas Angular 2 uses TypeScript version 1.8. This brings a lot of difference in the performance.

So, when building Angular applications, we need to have our TypeScript code converted into JavaScript code that browsers can understand. This process is called transpilation which is the combination of translate and compile. And that’s the job of the TypeScript compiler.

Important: Angular is not Angular JS.

Angular JS → Angular version 1.x

Angular → Angular version 2+

Typescript

Typescript over Javascript

TypeScript is (a superset of JavaScript that scales), kind of stricter version of Javascript provided with OOPS features.. That means any valid JavaScript code is valid TypeScript code.

Although, other alternative could be Dart, typescript is the most widely used language for Angular apps.

Basic difference in terms of Syntax

Note: Typescript is NOT ES6 or ES7. Browsers do not understand typescript , so the typescript code is transpiled to javascript first.

Creating an Angular App

source: https://programmingwithmosh.com/angular/angular-4-tutorial/

To install Angular 4, the Angular team came up with Angular CLI which eases the installation. You need to run through a few commands to install Angular 4.

So with Angular CLI in place, now we can create a new Angular project using the following command(s) in order:

[1]. install node.js (from nodejs.org and install the latest stable version).[2]. npm install -g @angular/cliNode comes with a tool called Node Package Manager or NPM, which is used for installing third-party libraries. In this tutorial, we’re going to use NPM to install Angular CLI. That is a command-line tool we use to create a new Angular project. It is also used for generating some boilerplate code during development (such as components, services, etc) as well as building an application for deployment. We do all this in the terminal.
[3]. ng new hello-world =>
we can access Angular CLI using ng. here, we are create a new Angular project using this command.
[4]. cd hello-world[5]. npm install => we install all the dependencies of our application.[6]. ng serve => compiles our application and hosts it using a lightweight web server. Now, we can access our application at http://localhost:4200. port 4200, which is the default port that angular–cli makes use of while compiling. You can change the port if you wish using the following command −ng serve --host 0.0.0.0 –port 4205Alternatively, you can use theng serve --opento let it automatically open the browser window running the angular application. Take a deep breath and here you go. Congratulations! You generated and served your first Angular 4 application.

Architecture of Angular Apps

The most fundamental building block in an Angular application is a component. You can think of a component as a view component. It represents a view or part of a view (what the user sees). A component consists of three pieces:

  • HTML markup: to render that view
  • State: the data to display on the view
  • Behaviour: the logic behind that view. For example, what should happen when the user clicks a button.

Also, at the root of the application, we have a component called AppComponent. This is the root of every Angular application, which is created by default will always remain the parent and the next components created will form the child components.

An Angular Component in Action

Now, let’s inspect a real component in action.

Back to our project, open up the src/app folder. Inside this folder, you should see the following files:

  • app.component.css
  • app.component.html
  • app.component.spec.ts
  • app.component.ts
  • app.module.ts

These files represent AppComponent, which is the root component for our application. In this particular case, all these files are inside the app folder. But when we generate a new component using Angular CLI, all the files that make up a component will be grouped by a folder.

So, in terms of the implementation, each component in an Angular project is physically implemented using four files:

  • A CSS file: where we define all the styles for that component. These styles will only be scoped to this component and will not leak to the outside. This is what Shadow DOM does. But not all browsers today support Shadow DOM. So, Angular uses a technique to emulate the Shadow DOM.
  • An HTML file: contains the markup to render in the DOM.
  • A spec file: includes the unit tests.
  • A TypeScript file: where we define the state (the data to display) and behavior (logic) of our component.

You will also see an app.module.ts file. This file defines the root module of our application and tells angular how to assemble the app.

The final file structure looks as follows −

Creating a new Component Using Angular CLI

Run the following command in the terminal, inside the project folder:

ng g c new-cmp

Here, g is short for generate, c is short for component and new-cmp is the name of our component.

The new-cmp folder is created under src/app folder. And following 4 files are created in the new-amp folder-

  • new-cmp.component.css − css file for the new component is created.
  • new-cmp.component.html − html file is created.
  • new-cmp.component.spec.ts − this can be used for unit testing.
  • new-cmp.component.ts − here, we can define the module, properties, etc.

And 5th file app.module.ts is updated to incorporate above new creation.

Open new-cmp.component.ts. This is what you should see:

import { Component, OnInit } from '@angular/core';@Component({
selector: 'app-product',
templateUrl: './new-cmp.component.html',
styleUrls: ['./new-cmp.component.css']
})
export class NewCmpComponent implements OnInit {
constructor() { }
ngOnInit() {
# ngOnInit is called by default when the class is executed.
}

Constructor is a reserved keyword in TypeScript. A method by that name is a special method in a class. This method is called automatically when we create an instance of that class.

ngOnInit is a special method in Angular. Angular calls this method when it creates an instance of this component and displays it to the user in the browser.

Module

Module in Angular refers to a place where you can group the components, directives, pipes, and services, which are related to the application.

To define module, we can use the NgModule. When you create a new project using the Angular –cli command, the ngModule is created in the app.module.ts file by default and it looks as follows −

app.module.ts file —

import { BrowserModule, FormsModule  } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { NewCmpComponent } from './new-cmp/new-cmp.component';
import { ChangeTextDirective } from './change-text.directive';
import { SqrtPipe } from './app.sqrt';
@NgModule({
declarations: [
SqrtPipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule,
RouterModule.forRoot([
{
path: 'new-cmp',
component: NewCmpComponent
}
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent {
title = 'Angular 4 Project!';
//array of months.
months = ["January", "Feburary", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
isavailable = true; myClickFunction(event) {
//just added console.log which will display the event details in browser on click of the button.
alert("Button is clicked");
console.log(event);
}
}

Templates

Angular 4 uses the <ng-template> as the tag instead of <template> which is used in Angular2. The reason Angular 4 changed <template> to <ng-template> is because there is a name conflict between the <template> tag and the html <template> standard tag.

Directives

Directives in Angular is a js class, which is declared as @directive. We have 3 directives in Angular. The directives are listed below −

Component Directives

These form the main class having details of how the component should be processed, instantiated and used at runtime.

Structural Directives

A structure directive basically deals with manipulating the dom elements. Structural directives have a * sign before the directive. For example, *ngIf and *ngFor.

Attribute Directives

Attribute directives deal with changing the look and behavior of the dom element. You can create your own directives as shown below.

How to Create Custom Directives?

We will create the directive using the command line. The command to create the directive using the command line is −

ng g directive nameofthedirectivee.gng g directive changeText

The above files, i.e., change-text.directive.spec.ts and change-text.directive.ts get created and the app.module.ts file is updated.

The ChangeTextDirective class is included in the declarations in the above file. The class is also imported from the file given below.

change-text. directive

import { Directive } from '@angular/core';
@Directive({
selector: '[changeText]'
})
export class ChangeTextDirective {
constructor() { }
}

Property (data) Binding & event Binding

In Angular, unlike vanilla JavaScript or jQuery, we don’t work directly with the DOM. So, we don’t write code like this:

$("#myElement").text("something")

Instead, we use property binding. Data Binding is available right from AngularJS, Angular 2 and is now available in Angular 4 as well.

Let me show you how that works.

Now, open up product.component.html. Replace all the markup there with:

<p>{{ title }}</p>

This special double curly brace syntax you see here is what we call interpolation in Angular. This syntax is a shorthand for the actual property binding syntax we have in Angular.

Similar to property binding, we have another concept in Angular called event binding. With property binding, we bind properties of DOM elements to fields/properties in our component. With event binding, we bind events of DOM elements (such as clicks) to methods in our component. So, for example, when the user clicks on a button, a method in our component will be called.

Note the difference between property and event binding syntax. We use curly brackets for property bindings and parenthesis for event binding. With this code, whenever our button is clicked, Angular calls the addItem() method in our component.

<p>{{ title }}</p>
<p>{{ itemCount }}</p>

Following is the syntax to define a button and add a function to it.

<button (click)="addItem($event)">Add</button>

Pipes in Angular 2/4 vs Filters in AngularJS

The | character is used to transform data. Following is the syntax for the same

{{ Welcome to Angular 4 | lowercase}}

Routing

import { RouterModule} from '@angular/router';

The url contains http://localhost:4200/new-cmp. Here, the new-cmp gets appended to the original url, which is the path given in the app.module.ts and the router-link in the app.component.html.

When a user clicks New component, the page is not refreshed and the contents are shown to the user without any reloading. Only a particular piece of the site code will be reloaded when clicked. This feature helps when we have heavy content on the page and needs to be loaded based on the user interaction. The feature also gives a good user experience as the page is not reloaded.

The <router-outlet></router-outlet> is used for navigation between one page to another.

Services

We might come across a situation where we need some code to be used everywhere on the page. It can be for data connection that needs to be shared across components, etc. Services help us achieve that. With services, we can access methods and properties across other components in the entire project.

To create a service, we need to make use of the command line. The command for the same is −

ng g service myservice

Following are the files gets created at the bottom in addition to existing files myservice.service.specs.ts and myservice.service.ts.

Again, before creating a new service, we need to include the service created in the main parent app.module.ts as we did in case of while creating DIRECTIVES, PIPES, etc. expect for this update

providers: [MyserviceService],

If you change the property of the service in any component, the same is changed in other components too. Let us now see how this works.

Http Service

Http Service will help us fetch external data, post to it, etc. We need to import the http module to make use of the http service.

import { HttpModule } from '@angular/http';

Conclusion:

The following table lists down a few important commands required while working with Angular 4 projects.

Whenever a new module, a component, or a service is created, the reference of the same is updated in the parent module app.module.ts.

Global State Management in Angular Applications:

One of the biggest challenges with any application is managing data. In the world of Angular, there are a lot of patterns to follow to manage your application. These typically involve using decorators like Input and Output, or things like RxJs Observables to watch for data changes. However, there is a reactive state technology that solves this challenge called NgRx.

What is Ngrx?

Ngrx is a set of Angular libraries for reactive extensions.

Two popular Ngrx libraries are:

[1]. Ngrx/Store, an implementation of the Redux pattern using the well-known RxJS observables of Angular 2. @ngrx/store is a library that tries to solve the problems of state management through the principles of Redux. The difference between Redux and @ngrx/store is that @ngrx/store is written specifically for Angular and it embraces the use of Observables from RxJS. The combination of redux principles and RxJS can be very powerful when it comes to writing reactive applications.

[2]. Ngrx/Effects, a library that allows the application to communicate with the outside world by triggering side effects.

NgRx is an open source library that provides reactive state management for your Angular applications. Inspired by Redux, NgRx provides a way to maintain data in your Angular application as a single source of truth. NgRx uses streams to interact with a data store. This data store connects to your components and services, and ultimately simplifies the entire process of data management in your Angular application. Instead of injecting services everywhere and managing communication between them, NgRx manages your application from one singular source. Using NgRx, you work with your application in terms of its overall state, instead of individual components.

How NgRx works

There are five parts that constitute NgRx:

  1. Store
  2. Reducers (and Meta-Reducers)
  3. Actions
  4. Selectors
  5. Effects

The basic implementation looks like the following:

  1. Your application’s state is maintained in the store. The store is immutable.
  2. Your application’s components can subscribe to the store and get automatic updates of state through selectors.
  3. Selectors enable components to get a slice (a part) of your application’s state, and also mutate state with selector functions.
  4. Actions modify the state of the store by using reducers (functions) that enable changes while keeping it immutable.
  5. Meta-Reducers (not shown) are hooks where you can pre or post-process actions before they get invoked.
  6. Effects occur as a result from actions, and can also create actions when called. Effects primary responsibility is to create async side-effects (like service calls to APIs), that ultimately generate other actions.

This is a big change in the way that traditional applications are built, and creates a paradigm that greatly simplifies complex applications.

NgRx can also simplify the architecture of your application, as you can use it to replace property and event bindings. This is obviously based on the project, and there are many ways to use a hybrid approach or not even use NgRx at all. For guidelines on structuring your application, I recommend the Pluralsight course “Angular NgRx: Getting Started” with Duncan Hunter and Deborah Kurata.

The last step before you see NgRx in action is to add on the NgRx Redux Devtools Extension to Chrome. You won’t be able to use this until you’ve setup NgRx, but it will enable you to view the store data while you are developing your application.

Redux (@ngrx/store) best practices

@ngrx/store is a library that tries to solve the problems of state management through the principles of Redux. The difference between Redux and @ngrx/store is that @ngrx/store is written specifically for Angular and it embraces the use of Observables from RxJS. The combination of redux principles and RxJS can be very powerful when it comes to writing reactive applications. Since a lot of Angular projects use @ngrx/store, it might be a good idea to write down some best-practices.

In short, they are very different libraries for very different purposes, but yes there are some vague similarities.

Redux is a tool for managing state throughout the application. It is usually used as an architecture for UIs. Think of it as an alternative to (half of) Angular.

RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises.

Must Reads @

https://programmingwithmosh.com/angular/angular-4-tutorial/

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app