Angular

This is a short introduction to get you start and experience with Angular. For more information, please refer to Angular.io.

(Please tell me if you find any errors or omissions in the document, 3-April-2021)

Overview

  What is Angular?  

  • A JavaScript front-end web application framework that provides a very structured method of creating websites and web applications.
  • A JavaScript library that enforces a structured Model View Controller (MVC) framework
  • One of the most widely used JavaScript client-side frameworks

  JavaScript Client-Side Frameworks  

  • JavaScript client-side applications run on the user's device, and thus shift the workload to the user's hardware and away from the server.
  • Advantages:
    • Simplicity
    • Rapid development
    • Speed of operation
    • Testability
    • Ability to package the entire application and deploy it to all mobile devices and the Web
      • Build an application once and deploy and run it anywhere, on any platform, with no modifications

  Why Angular?  

  • Angular framework forces MVC and makes it easy to implement MVC properly
  • The declarative style of Angular HTML templates makes the intent of the HTML more intuitive and makes the HTML easier to maintain
  • The model portion of Angular is similar to basic JavaScript objects, making it easy to manipulate, access, and implement
  • Angular uses a declarative approach to extend the functionality of HTML by having a direct link between the HTML declaratives and the JavaScript functionality behind them
  • Angular provides a very simple and flexible filter interface that enables you to easily format data as it passes between components
  • Angular applications tend to use a fraction of the code that traditional JavaScript applications use because you need to focus only on the logic and not all the little details, such as data binding
  • Angular requires a lot less Document Object Model (DOM) manipulation than traditional methods and guides you to put the manipulations in the correct locations in applications. This makes it easier to design applications based on presenting data than on DOM manipulation
  • Angular provides several built-in services and enables you to implement your own in a structured and reusable way. This makes the code more maintainable and easier to test.
  • The separation of concerns makes it easy to test web applications and supports a test-driven development approach (TDD)
Note: AngularJS is the official branding (reserved for AngularJS 1.x), which is the early version of Angular. Because the new version of Angular used TypeScript (instead of JavaScript) as the primary language, the JS was dropped.

Single-Page Application (SPA)


Single-page application
  • Angular is most often used to build applications that conform to the single-page application (SPA) concept
  • SPAs are applications that have one entry point HTML page.
  • All the application content is dynamically added to and removed from the one page

Angular Applications

  • Angular supports both MVC and MVVM
    • Separate the business logic in code from the view and the model, making the code easy to follow and maintain
    • Model is the data source
    • View is the rendered web page
    • Controller handles the interaction between model and view
  • Angular uses two-way data binding, allowing view to be updated promptly

Overview Angular MVC application

  • Once the Angular application is launched, the model, view, controller, and all HTML documents are loaded on the user's device and run entirely on the user's hardware
  • The backend components, may be located on a private web server or in the cloud, perform all business logic and business processes
Note: To create an Angular app, ng new project-or-app-name

Components and Features

To get started with Angular, let's understand the various components and features that will be implemented and how they interact with each other.

  Module  

  • Organize components in an application
  • Provides a namespace that enables you to reference directives, and other components based on model name
    • Make it easy to package and reuse parts of an application
  • Every application has at least one module, each of which is identified with the @NgModule decorator
  • Other modules can be added to the main module as dependencies
  • The main Angular module (AppModule) acts similar to the root namespace (or a package) in Java
  • The @NgModule declarator has several properties:
    • declarations — specify the components that are defined in this module. Note: components must be declared in NgModule before they can be used.
    • exports — specify which components should be visible and usable in the component templates of other NgModules.
    • imports — describe which dependencies this module has.
    • providers — for dependency injection. When module A requires module B to run, B is a dependency of A. Therefore, B must be imported into A, using   import {B} from 'name-of-module-or-class-B-is-in';
    • bootstrap — instruct Angular which component must be loaded as the top-level component when this module is used to bootstrap an app
  • To create a module, ng generate module module-name

  Component  

  • Basic building block of UIs and Angular applications
  • Control one or more sections (i.e., views) on the screen
  • Each component is composed of three parts:
    • Component decorator (@Component)
    • View
    • Controller
  • To create a component, ng generate component component-name
  • Example
    import { Component } from '@angular/core';
    @Component( {
       selector: 'name-of-this-component',
       templateUrl: './view-this-component-will-handle.html',
       styleUrls: ['./list-of-style-file-to-be-used.css'] 
    })
    export class AppComponent {
       property-name = 'value';
       function-name(param1: data-type, param2: data-type): return-type {
           some-statements-for-this-function-or-controller
       }
    }   

  Data Model  

  • A JavaScript representation of data used to populate a view presented on a web page
  • The data can come from any source, such as a database, a remote web service, the client-side Angular code, or dynamically generated by the backend web components
  • Example
    export class model-name {
       constructor(
          public property1: data-type,
          public property2: data-type,
          public property3: data-type
       ) {}
    }   
  • To create a data model, ng generate class model-or-class-name

  Views with Templates and Directives  

  • HTML web pages are based on a DOM
    • Each HTML element is represented by a DOM object
    • A web browser renders the HTML element based on the DOM object's properties
  • Most dynamic web applications use JavaScript or a JavaScript-based library (such as jQuery) to manipulate a DOM object to change the behavior and appearance of the rendered HTML element
  • Angular uses directives
    • Directives have two parts:
      • Extra attributes, elements, and CSS classes that are added to an HTML template
        • Extend the HTML tags and attributes
      • JavaScript code that extends the behavior of the DOM
        • Extend the HTML capability
  • With directives, the intended logic for visual elements is indicated by the HTML template
    • Easy to follow
    • Not hidden within JavaScript code
  • The built-in Angular directives handle most of the necessary DOM manipulation functionality to bind the data and event directly to the HTML elements in the view
  • Directives can be customized to manipulate DOM as needed

  Expressions  

  • Expressions may be added inside the HTML template
  • Expressions are evaluated and then their results are dynamically added to a web page

  Data Binding  

  • One of the best features of Angular
  • A process of linking data from the model with what is displayed on the page
  • In Angular, data binding is a two-way process:
    • When data are changed on a web page, the model is updated
    • When data are changed in the model, the web page is automatically updated
  • The model is the source for data represented to the user, and the view is just a projection of the model

  Services  

  • Objects that provide functionality for a web application
  • Example: a common task of web applications is to perform asynchronous requests to a web server. Angular provides an HTTP service that houses all the functionality to access a web server.
  • Angular provides many built-in service components for basic uses, such as HTTP requests, logging, parsing, and animation

  Dependency Injection  

  • A process in which a code component defines dependencies on other components
  • When the code is initialized, the dependent component is made available for access within the component
  • Example: for a module that requires access to the web server via HTTP requests, the HTTP service can be injected into the module (making its functionality to be available in the module code)

Life Cycle

  Three phases of Angular life cycle  

  • The bootstrap phase
    • Occur when the Angular JavaScript library is loaded to the browser
    • Angular initializes its own necessary components
    • Then, your module is initialized
    • Your module is loaded
    • Any dependencies are injected into your module and made available to code within the module
  • The HTML compilation phase
    • Initially, when a web page is loaded, a static form of the DOM is loaded in the browser
    • During the compilation phase, the static DOM is replaced with a dynamic DOM that represents the Angular view
    • Two parts:
      • Traversing the static DOM and collecting all the directives
      • Linking the directives to the appropriate JavaScript functionality in the Angular built-in library or custom directive code
  • The runtime data binding phase
    • The runtime phase exists until the user reloads or navigates away from the current page
    • Any changes in the model are reflected in the view
    • Any changes in the view are directly updated in the model
    • Note: Angular behaves differently from traditional methods of binding data.
      • Traditional methods combine a template with data received from the engine and then manipulate the DOM each time the data changes
      • Angular compiles the DOM only once and then links the compiled template as necessary (potentially makes the application more efficient than traditional methods)
The three phases happen each time a web page is loaded in the browser.

Similar to any app, an Angular app has a main entry point. After the app is run (using the command ng serve), ng will look at the angular.json file to find the entry point to the Angular app. At the high level:
  • angular.json specifies a "main" file, which in this case is main.ts
  • main.ts is the entry-point for the app and thus it bootstraps the app
  • The bootstrap process boots an Angular module
  • The AppModule is used to bootstrap the app. AppModule is specified in src/app/app.module.ts
  • AppModule specifies which component to use as the top-level component, which is AppComponent (from in-class examples)
  • AppComponent has <app-root> tags (specified as a selector in app.component.ts file)

Separation of Responsibilities

The important part of designing Angular applications is the separation of responsibilities. This ensures that code is readable, maintainable, and testable.

  Guideline when implementing Angular applications  

  • The view acts as the official presentation structure for the application
    • Indicate any presentation logic as directives in the HTML template of the view
  • If you need to perform any DOM manipulation, do it in a built-in or your own custom directive JavaScript code
  • Implement any reusable tasks as services and add them to your modules by using dependency injection
  • Ensure that the view template reflects the current state of the model
  • Define controllers within the module namespace and not globally. This ensures that the application can be packaged easily and prevents overwhelming the global namespace.