You are on page 1of 30

Angular Concepts

1. Core concepts of Angular components

Core concepts of Angular


 Modules
 Components
 Component metadata
 Templates that define views
 Data binding
 Directives
 Pipes
 Services and dependency injection
 Routing

2. Concept of modules

An angular module is one of the basic building block of any angular applications like component.


A modules consist of one or more components and it does not control any html
view. Modules configure the injector and the compiler and help us to organize related things together.

3. Fundamentals of services and Dependency injection

4. Angular life cycle hooks

Life cycle hooks sequence:


After your application instantiates a component or directive by calling its constructor, Angular calls the hook methods
you have implemented at the appropriate point in the lifecycle of that instance.
1) OnChanges
Called before ngOnInit() and whenever one or more data-bound input properties change. If your component has
no inputs or you use it without providing any inputs, the framework will not call ngOnChanges().
2) OnInit - Called once, after the first ngOnChanges().
3) DoCheck
Called immediately after ngOnChanges() on every change detection run, and immediately after ngOnInit() on
the first run.
4) AfterContentInit
Called once after the first ngDoCheck().
5) AfterContentChecked
Called after ngAfterContentInit() and every subsequent ngDoCheck()
6) AfterViewInit
Called once after the first ngAfterContentChecked()
7) AfterViewChecked - Called after the ngAfterViewInit()  and every subsequent ngAfterContentChecked().
8) OnDestroy
Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive.

 Unsubscribe from Observables and DOM events.


 Stop interval timers.
 Unregister all callbacks that the directive registered with global or application services.
5. Basics of component Interaction

Basics of component Interaction

 Pass data from parent to child with input binding

 Intercept input property changes with a setter

Use an input property setter to intercept and act upon a value from the

 Intercept input property changes with ngOnChanges()

 Parent listens for child event

The child component exposes an EventEmitter property with which it emits events when something happens.
The parent binds to that event property and reacts to those events.The child's EventEmitter property is an output
property, typically adorned with an @Output() decorator

 Parent interacts with child via local variable

A parent component cannot use data binding to read child properties or invoke child methods. You can do both
by creating a template reference variable for the child element and then reference that variable within the parent
template.
 Parent and children communicate via a service
A parent component and its children share a service whose interface enables bi-directional communication
within the family.The scope of the service instance is the parent component and its children. Components outside this
component subtree have no access to the service or their communications.

6. How to style anglular components


7. How to create dynamic components
8. What are directives? How structural directive and attribute directives works.

Directives:
Angular framework migrated from directives to components in Angular 2. Remember that all components are directives.
Angular has three kinds of directives.
1) Component - @Component() - directives with a template.

2) Structural Directives – It alters the layout of the DOM by adding,replacing and removing its elements.Two examples
are NgFor , NgIf-input variables and NgSwitch.
3) Attribute Directives - It changes the appearance or behaviour of a DOM element.These directives look like regular
HTML attributes in templates. Attribute directives are used as attributes of elements. The built-in
NgStyle,NgStyle,NgModel([ngModel]) directive for example.
Create Custom Directive
MyErrorDirective:

import {Directive, ElementRef} from '@angular/core';


@Directive({
selector:'[my-error]'
})
export class MyErrorDirective{
constructor(elr:ElementRef){
elr.nativeElement.style.background='red';
}
}

AppComponent:

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


@Component({
selector: 'my-app',
template: `<h1 my-error>Hello {{name}}</h1>`,
})
export class AppComponent { name = 'Angular'; }

AppModule :
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyErrorDirective } from './app.myerrordirective';

import { AppComponent } from './app.component';

@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, MyErrorDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

9. How pipes works in angular

Pipes
Your templates can use pipes to improve the user experience by transforming values for display. For example, use
pipes to display dates and currency values that are appropriate for a user's locale. Angular provides predefined pipes for
common transformations, and you can also define your own pipes.In other words, Pipes are simple functions you can use
in template expressions to accept an input value and return a transformed value. To apply a pipe, use the pipe operator (|) within a
template expression
 DatePipe: Formats a date value according to locale rules.
o <p>The hero's birthday is {{ birthday | date }}</p>
o <p>The hero's birthday is {{ birthday | date : "MM/dd/yy"}}</p>
 UpperCasePipe: Transforms text to all upper case.
o {{ birthday | date | uppercase}}
 LowerCasePipe: Transforms text to all lower case.
 CurrencyPipe: Transforms a number to a currency string, formatted according to locale rules.
 If the pipe accepts multiple parameters, separate the values with colons. For example,
 {{ amount | currency:'EUR':'Euros '}} adds the second parameter, the string literal 'Euros ', to the output string.
 DecimalPipe: Transfo a number into a string with a decimal point, formatted according to locale rules.
 PercentPipe: Transforms a number to a percentage string, formatted according to locale rules.
Custom Pipe(exponentialStrength):
import { Pipe, PipeTransform } from '@angular/core';
/*
* Raise the value exponentially
* Takes an exponent argument that defaults to 1.
* Usage:
* value | exponentialStrength:exponent
* Example:
* {{ 2 | exponentialStrength:10 }}
* formats to: 1024
*/
@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
transform(value: number, exponent: number): number {
return Math.pow(value, isNaN(exponent) ? 1 : exponent);
}
}

Example for Custom Pipe demo(PowerBoosterComponent)

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

@Component({
selector: 'app-power-booster',
template: `
<h2>Power Booster</h2>
<p>Super power boost: {{2 | exponentialStrength: 10}}</p>
`
})
export class PowerBoosterComponent { }

10. Usage of Forms, like reactive forms and template driven forms, with form validation
11. Using Observables and RxJs

RxJS is a reactive streams library used to work with asynchronous streams of data. It is a third-party
library used by the Angular team. Observables, in RxJS, are used to represent asynchronous
streams of data. Observables are a more advanced version of Promises in JavaScript.

12. How NgModules works and what its components.

NgModules help organize an application into cohesive blocks of functionality.

An NgModule is a class adorned with the @NgModule decorator function. @NgModule takes a
metadata object that tells Angular how to compile and run module code. It identifies the module’s
own components, directives, and pipes, making some of them public so external components can
use them. @NgModule may add service providers to the application dependency injectors. And there
are many more options covered here.

Many Angular libraries are modules (such as FormsModule, HttpModule, and RouterModule). Many
third-party libraries are available as NgModules (such as Material Design, Ionic, AngularFire2).

NgModules consolidate components, directives, and pipes into cohesive blocks of functionality, each
focused on a feature area, application business domain, workflow, or common collection of utilities.
Modules can also add services to the application. Such services might be internally developed, such
as the application logger. Services can come from outside sources, such as the Angular router and
Http client.

Modules can be loaded eagerly when the application starts. They can also be lazy loaded
asynchronously by the router.

An NgModule is a class decorated with @NgModule metadata. The metadata do the following:

 Declare which components, directives, and pipes belong to the module.


 Make some of those classes public so that other component templates can use them.
 Import other modules with the components, directives, and pipes needed by the components
in this module.
 Provide services at the application level that any application component can use.

Every Angular app has at least one module class, the root module. You bootstrap that module to
launch the application.

The root module is all you need in a simple application with a few components. As the app grows,
you refactor the root module into feature modules that represent collections of related functionality.
You then import these modules into the root module.

13. Basics of HttpClient module.


14. Working of angular Routing and Navigation
15. Basics of server side rendering

  Angular Questions
Q1: What is Routing Guard in Angular?    
Angular’s router provides a feature called Navigation Guards
There are five different guard types we can use to protect our routes:
 CanActivate - Decides if a route can be activated
 CanActivateChild - Decides if children routes of a route can be activated
 CanDeactivate - Decides if a route can be deactivated
 CanLoad - Decides if a module can be loaded lazily
 Resolve - This guard delays the activation of the route until some tasks are complete. You can use
the guard to pre-fetch the data from the backend API, before activating the route

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


import { CanLoad, Route, Router } from '@angular/router';
 
@Injectable()
export class AuthGuardService implements CanLoad {
  
  constructor(private router: Router) {
  }
 
  canLoad(route: Route): boolean {
    
    let url: string = route.path;
    console.log('Url:'+ url);
    if (url=='admin') {
      alert('You are not authorised to visit this page');
      return false;
    }  
    return true;
  }
}

const routes: Routes = [


  {path: "admin", loadChildren:'./admin/admin.module#AdminModule', canLoad:[AuthGuardService]},
  {path: "test", loadChildren:'./test/test.module#TestModule', canLoad:[AuthGuardService]},
];

Q2: What is a module, and what does it contain?    


Q3: What are pipes? Give me an example.    
Q4: What is a component? Why would you use it?    
Q5: What's the difference between an Angular component and module?    
Q6: What is a service, and when will you use it?    
Q7: What is the equivalent of ngShow and ngHide in Angular?    
Q8: How can I select an element in a component template?    
<input #myname>
@ViewChild('myname') input;
element

ngAfterViewInit() {
console.log(this.input.nativeElement.value);
}

Q9: What is the difference between "@Component" and "@Directive" in Angular?    


Q10: How would you protect a component being activated through the router?    
Q11: How would you run unit test?    
Q12: What is the difference between Structural and Attribute directives in Angular?    
Angular has three kinds of directives.
4) Component - @Component() - directives with a template.

5) Structural Directives – It alters the layout of the DOM by adding,replacing and removing its elements.Two examples
are NgFor , NgIf-input variables and NgSwitch.
6) Attribute Directives - It changes the appearance or behaviour of a DOM element.These directives look like regular
HTML attributes in templates. Attribute directives are used as attributes of elements. The built-in
NgStyle,NgStyle,NgModel([ngModel]) directive for example.

Q13: What is the purpose of base href tag?    


Q14: What is an observer?    

Here is a simple visual to see the difference:


As seen above ... an Observable is a stream of events or data. They are often returned from Angular methods, such as
the http.get and the myinputBox.valueChanges.

Subscribing "kicks off" the observable stream. Without a subscribe (or an async pipe) the stream won't start emitting values. It's
similar to subscribing to a newspaper or magazine ... you won't start getting them until you subscribe.

The subscribe method takes in an observer. An observer has three methods:

 The method to process each time an item is emitted from the observable.
 The method to process any error that occurs.
 The method to clean up anything when the observer completes. This last one is seldom used when working with Angular's
observables.

Q15: What is an observable?

Observables provide support for passing messages between parts of your application. They are
used frequently in Angular and are the recommended technique for event handling, asynchronous
programming, and handling multiple values.
  
Q16: What are observables?    
Q17: What is a bootstrapping module?    
Q18: What is interpolation?    
One way binding

Q19: Explain the difference between `Promise` and `Observable` in Angular?


Observable vs Promise
1) Observable emits multiple values over a period of time but promise emits single vale
2) Observable is lazy loading but promise is not lazy loading.
3) Observable can be cancelled by using unsubscribe() method but promise cannot be cancelled
4) Observable provides operators like map, forEach, filter, reduce, retry, retryWhen etc.

we can use some methods from the RxJS library that create simple observables of frequently used types:

 of(...items)—Returns an Observable instance that synchronously delivers the values provided as arguments.
 from(iterable)—Converts its argument to an Observable instance. This method is commonly used to convert an
array to an observable.
  
Q20: Explain the difference between "Constructor" and "ngOnInit"    
Q21: Why should `ngOnInit` be used, if we already have a `constructor`?    
Q22: How to bundle an Angular app for production?    
Q23: What is difference between "declarations", "providers" and "import" in NgModule?    
Q24: What is Reactive Programming and how to use one with Angular?    
Q25: Why would you use a spy in a test?    
Q26: What is TestBed?    
TestBed is the primary api for writing unit tests for Angular applications and libraries. Note: Use TestBed in tests. It will
be set to either TestBedViewEngine or TestBedRender3 according to the compiler used.

Q27: What is Protractor?    


Q28: What is the point of calling "renderer.invokeElementMethod(rendererEl, methodName)"?    

What are the difference between Renderer and ElementRef in angular 2?

ElementRef vs. Renderer -


In Angular Renderer and ElementRef are used for DOM Manipulation and Renderer and ElementRef are used together to get
full platform abstraction.

Renderer –
Renderer is a class that is a partial abstraction done the DOM manipulations and the DOM manipulating is not breaking server
side rendering or web workers.

ElementRef –
ElementRef is a class that is a partial abstraction done the DOM Manipulations without breakable environments and it also can
hold a reference to a DOM elements.

If “ElementRef” is injected to a component, the injected instance is a reference to the host element of the current component.

The ways to get an ElementRef instance looks like,


1.     @ViewChild()
2.     @ViewChildren()
3.     @ContentChild()
4.     @ContentChildren()
In this case the ElementRef is a reference to the matching elements in the templates.

Do notice that you should refrain from using ElementHref as it flagged with a security risk?
If you allow direct access to the DOM, it can make your application more vulnerable to XSS attacks. So make sure, when you
are using to ElementRef in your app code.

What is the point of calling renderer.invokeElementMethod(rendererEl, methodName)?

//our root app component


import {Component, ElementRef} from 'angular2/core'
import * as browser from 'angular2/platform/browser'
import {Ruler, Rectangle} from 'angular2/src/platform/browser/ruler.js'

@Component({
selector: 'my-app',
providers: [ElementRef],
template: `
<div>
<h2>Hello {{name}}</h2>
<p>H2 Height: {{rect.height}}</p>
<p>H2 Width: {{rect.width}}</p>
</div>
`,
directives: []
})
export class App {
constructor(element: ElementRef) {
this.name = 'Angular2'
this.element = element;
this.ruler = new Ruler(new browser.BrowserDomAdapter());
this.rect = {};
}
ngOnInit() {
var vm = this;
var measure = this.ruler.measure(this.element);
measure.then(function (rect) {
console.log('Rect', rect);
vm.rect = rect;
});
}
}

Q29: How would you control size of an element on resize of the window in a component?    
Q30: What is Redux and how does it relate to an Angular app?    
Q31: When would you use eager module loading?    
Q32: What are the Core Dependencies of Angular 7?    

Q33: Why Incremental DOM Has Low Memory Footprint?    

Why does an Incremental DOM have a Low Memory Footprint? Virtual DOM generates a whole


tree from scratch every time you rerender. On the other hand, Incremental DOM doesn’t require any
memory to re-render the view if it doesn’t change the DOM. We only need to allocate the memory
when the DOM nodes are added or removed.
Q34: What are the ways to control AOT compilation?    

Q35: What is Angular Universal?    

Angular Universal is the process of server-side rendering (SSR) your application to HTML on the


Server (ie: Node.js). Typical Angular applications are Single-Page Applications (aka SPA’s) where the
rendering occurs on the Browser. This process can also be referred to as client-side rendering (CSR).
Q36: Do I need a Routing Module always?  

No, the Routing Module is a design choice. You can skip routing Module (for example, AppRoutingModule) when the
configuration is simple and merge the routing configuration directly into the companion module (for example, AppModule). But
it is recommended when the configuration is complex and includes specialized guard and resolver services.
 
Q37: What is the purpose of Wildcard route?    

A Wildcard route has a path consisting of two asterisks (**). It matches every URL, the router will select this route if it can’t
match a route earlier in the configuration. A Wildcard Route can navigate to a custom component or can redirect to an
existing route.

What is redirectTo in angular?


redirectTo?: string. A URL to redirect to when the path matches. Absolute if the URL begins with a slash (/),
otherwise relative to the path URL. Note that no further redirects are evaluated after an absolute redirect. When not
present, router does not redirect.

What is the use of routing in angular?


Routing in Angular helps us navigate from one view to another as users perform tasks in web apps.

Q38: What is activated route?    

Q39: What is router state?  

a router state is an arrangement of application components that defines what is visible on the
screen. In this article we will look at RouterState in depth.
 
Q40: What is router outlet?    

The router-outlet is a directive that's available from the @angular/router package and is used by the router to mark where in
a template, a matched component should be inserted.
Thanks to the router outlet, your app will have multiple views/pages and the app template acts like a shell of your application.
Any element, you add to the shell will be rendered in each view, only the part marked by the router outlet will be changed
between views.

Q41: What are dynamic components?    

How to create Dynamic components


ViewContainerRef is automatically attached to that component, so every component has its own ViewContainerRef,
you can access it either dependency injection or from a view child. ViewContainerRef helps you to add a component
programmatically ( not from view). you can add as many components as you want. To create component you need to use stuff
like ViewContainerRef, ComponentResolveFactory, ComponentRef, etc.
The most important thing to notice is that all the components you will add by ViewContainerRef will be siblings for
each other and not having a parent-child relationship.
It will be a sibling of H4 element, and child of app-child component. you can reach that possibility using ViewChild decorator.

ComponentFactoryResolver
ViewContainerRef only knows how to attach/remove a component to view. it doesn’t know how to create a component
instance. so It needs someone who will create a component, that’s what ComponentFactoryResolver does.

Using Dependency Injection:


import {DynamicComponent} from "../dynamic/dynamic.component";
@Component({
selector: 'app-child',
template: ' <h4> I am child </h4> ',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

constructor(private vf:ViewContainerRef,private componentFactoryResolver:ComponentFactoryResolver) { }


ngOnInit() {
//This pieces of code adds dynamic component ( Just trust me for now )
let resolver = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
let componentFactory = this.vf.createComponent(resolver);
}
}
Using @ViewChild({read:ViewContainerRef}):

import {DynamicComponent} from "../dynamic/dynamic.component";


import { Component, ViewChild, ViewContainerRef } from '@angular/core';

@Component({
selector: 'app-child',
template: ' <h4 #vf> I am child </h4> ',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@ViewChild("vf",{read:ViewContainerRef})
vf:ViewContainerRef;

constructor(private componentFactoryResolver:ComponentFactoryResolver) { }

ngAfterViewInit() {
//This pieces of code adds dynamic component ( Just trust me for now )
let resolver = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
let componentFactory = this.vf.createComponent(resolver);

}
}

Q42: Explain how custom elements works internally?    


Q43: What are the utility functions provided by RxJS?    
Q44: How do you perform error handling in observables?    

Q45: What is multicasting?  

Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let’s demonstrate the
multi-casting feature,

var source = Rx.Observable.from([1, 2, 3]);


var subject = new Rx.Subject();
var multicasted = source.multicast(subject);
// These are, under the hood, `subject.subscribe({...})`:
multicasted.subscribe({ next: (v) => console.log('observerA: ' + v) });
multicasted.subscribe({ next: (v) => console.log('observerB: ' + v) });
 
Q46: What is subscribing?    
Q47: How do you perform Error handling for HttpClient?    
Q48: What is a parameterized pipe?    
Q49: How do you categorize data binding types?    

Q50: What happens if you use script tag inside template?    

Angular recognizes the value as unsafe and automatically sanitizes it, which removes the script tag but keeps safe content such as the text
content of the script tag. This way it eliminates the risk of script injection attacks. If you still use it then it will be ignored and a warning
appears in the browser console.

Let's take an example of innerHtml property binding which causes XSS vulnerability,

export class InnerHtmlBindingComponent {


// For example, a user/attacker-controlled value from a URL.
htmlSnippet = 'Template <script>alert("0wned")</script> <b>Syntax</b>';
}

Q51: What are the lifecycle hooks for components and directives?    
Q52: When should I store the "Subscription" instances and invoke `unsubscribe()` during the NgOnDestroy life cycle and
when can I simply ignore them?    
Q53: How to set headers for every request in Angular?    

Q54: How to detect a route change in Angular?  

class MyClass {
constructor(private router: Router) {
router.events.subscribe((val) => {
// see also
console.log(val instanceof NavigationEnd)
});
}
}
 
Q55: What is the need for SystemJS in Angular?    
Q56: Are there any pros/cons (especially performance-wise) in using local storage to replace cookie functionality?    
Q57: What does "detectChanges" do in Angular jasmine tests?    
detectChanges() tells Angular to run change-detection. Finally! Every time it is called, it updates data bindings like ng-if,
and re-renders the component based on the updated data. Calling this function will cause ngOnInit to run only the first time it
is called.

Q58: Why would you use renderer methods instead of using native element methods?    
Q59: What would be a good use for NgZone service?    
Q60: What is Zone in Angular?    
Q61: How would you insert an embedded view from a prepared TemplateRef?    
Q62: What is ngUpgrage?    
Q63: Name and explain some Angular Module Loading examples    
Q64: Why would you use lazy loading modules in Angular app?    
Q65: When does a lazy loaded module is loaded?    
Q66: What is Ivy Renderer? Is it supported by Angular 7?    
Q67: What is incremental DOM? How is it different from virtual DOM?    

Incremental DOM Angular Ivy is based on the incremental DOM, which means that every component is
compiled into a series of instructions. These instructions are responsible for creating DOM trees and
updating them whenever a data change occurs. So the question you need to ask, why incremental
DOM and not the virtual DOM?

Q68: Why do we need compilation process?    


Q69: What are the mapping rules between Angular component and custom element?    
Q70: Do I need to bootstrap custom elements?    
Q71: What is the difference between pure and impure pipe?  
A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. An impure pipe is
called for every change detection cycle no matter whether the value or parameter(s) changes
 
Q72: What is the difference between BehaviorSubject vs Observable?    
Q73: What is the Angular equivalent to an AngularJS "$watch"?    
Q74: Is there no equivalent to `$scope.emit()` or `$scope.broadcast()` in Angular?    
Q75: Name some differences between SystemJS vs WebPack?    
Q76: Could you provide some particular examples of using ngZone?    
Q78: What is the default compilation for Angular 5?    
Q79: Just-in-Time (JiT) vs Ahead-of-Time (AoT) compilation. Explain the difference.    
Q80: Do you know how you can run angularJS and angular side by side?    
Q81: How would you extract webpack config from angular cli project?    
Q82: Why angular uses url segment?    
Q83: When to use query parameters versus matrix parameters?    
Q84: Why Incremental DOM is Tree Shakable?    

The Tree Shakeable Providers are used to define services and to be used by the dependency injection
system in the Angular. It is used in a way that improves the performance of the angular application.

The Tree Shakeable Provider mechanism provides the benefits of tree shaking performance and
dependency injection. The tree shaking mechanism refers to the process of removing unused code and
including only the code that is needed for the application to run.

Q85: What are observable creation functions?


Q86: what is the use of polyfills.ts in angular application

polyfills.ts file is auto generated while creating an Angular application using Angular Cli. Can anyone
explain me what is the use of polyfills.ts file in Angular application. Polyfills in angular are few lines of
code which make your application compatible for different browsers.

Angular JS Angular 2
Released by Google in the year 2010. Released in Sept 2016.
JavaScript-based framework for creating SPA. Complete re-write of AngularJS version.
It’s updated version regularly released because of
Still supported but no longer will be developed.
Semantic Versioning.
The architecture of Angular 2 is based on
The architecture of AngularJS is based on MVC.
service/controller.
AngularJS was not developed with a mobile base in
Angular 2 is a mobile-oriented framework.
mind.
AngularJS code can write by using only ES5, ES6, We can use ES5, ES6, Typescript to write an
and Dart. Angular 2 code.
Nowadays, the controllers are replaced by
Based on controllers whose scope is now over. components, and Angular two is completely
component based.
Factory, service, provider, value and constant are The class is the only method to define services in
used for services Angular2
Run on only client-side Runs on client-side & server-side
ng-app and angular bootstrap function are used to
bootstrapmodule() function is used to initialize
initialize

Difference between Angular 2 and Angular 4


Following is the key difference between Angular 2 Vs Angular 4:

Angular 2 Angular 4
Angular 4.0 has reduced the bundled file size by
The code generated using Angular 2 is bigger, and
60%. Thus code generated is reduced which helps
the file size is also larger.
to accelerate the application performance.
Angular two is not backward compatible with Angular four is backward compatible with Angular 2
Angular JS. for most applications.
There is no specific no proper disapproval phases to There will be proper disapproval phases to allow
adjust codes. developers to adjust their code
Animation features are pulled out of @angular/core
There is no animation feature offers in Angular 2.
and included into their package

Difference between Angular 4 and Angular 5


Here is the difference between Angular 4 Vs Angular 5:

Angular 4 Angular 5
New Router
Support for Router ParamMap Lifecycle
Event
Compiler
Dynamic Components with NgComponentOutlet Improvemen
ts
Angular 5
comes with
build
optimizer
TypeScript 2.4 with this version that functions as a JavaScript superset that can be used for
which is a
optional static typing, interfaces, and classes
part of the
platform’s
command
like a tool.
Optimization
with
HTTP Request Simplified
HttpClient
Feature
Internationali
Includes Animation Package zed Date &
Currency

Differences between Angular 8 and Angular 9


Angular 8 Angular 9
Ivy Engine Default Ivy in v9

Web Workers Phantom Template Variable Menace

Improvement in ng-upgrade Service Worker Updates

Lazy Loading Dependency Injection Changes in Core

Support for Node 10 i18n Improvements

CLI workflow improvements More reliable ng update

Upgrading Angular Material API Extractor Updates

TypeScript 3.4 support Typescript 3.7 support

Improved Web Worker Bundling ModuleWithProviders Support

Differential Loading Component Harness

Angular 9 Angular 10

Typescript 3.7 Typescript 3.9

Welcome Default Ivy Converting pre-Ivy code

Service Worker Updates Compiler Update

i18n Improvements Language Service

Enhancement of Language Service TSLib 2.9

Dependency Injection Changes in Core TSLint v6

ModuleWithProviders Support Localization

API Extractor Updates New Default Browser Configuration

Component Harness  Deprecation of ESM5 or FESM5

More reliable ng-update Optional Stricter Settings

Angular 10 Angular 11

Typescript 3.9 Typescript 4.0

Enabled ES5 builds  Faster Builds 

Language-service-specific compiler Ngcc compiler

Optional Stricter Settings Webpack 5 Support


Angular 10 Angular 11

Converting pre-Ivy code Automatic Inlining of Fonts

TSLint v6 Migration to ESLint

Deprecation of ESM5 or FESM5 bundles Deprecation of  IE 9, 10, and IE mobile

Recovered Service Worker stores  Clear API surface

Updated to TSLib 2.9 Updates on Operation Byelog

New Default Browser Configuration Updated Language Service Preview

Angular v11 Angular v12

Typescript 4.0 Typescript 4.2

Webpack 5 Support Webpack 5.37 Support

Migration to ESLint Migrating from legacy i18n message IDs

Deprecation of IE 9, 10, and IE mobile. Deprecating support for IE11.

Updates on Operation Byelog. Improved component tests harness.

Updated Language Service Preview. Http improvements.

strict checks with a flag. Default strict mode

Roadmap to provide early feedback Roadmap to inform about the priorities of the Angular team

Updated Language Service Preview Migration to default IVY-based language service

New Default Browser Configuration Updated Language Service Preview

Improved Ngcc compiler Improved logging and reporting

Summary
 AngularJS is an open-source front-end web framework based on JavaScript to build dynamic
web applications.
 Angular 2 is an AngularJS version built around the concept of the component, which allows
building JavaScript classes. After releasing Angular JS, the Angular team released Angular 2,
which is a complete rewrite of the original Angular 1 or AngularJS.
 All package names were assigned version 2, but router package by mistaken was given version
3. Therefore, the development team skipped Angular Version 3 and directly named it version 4
to maintain compatibility with Angular Router’s version.
 Angular 4 is a web application framework for building JavaScript applications. It supports
TypeScript, which compiles to JavaScript and displays the same in the browser.
 Angular 5 is an open-source web application framework which is based on TypeScript. There
are lots of new features and improvements done in this version like dependency injection,
declarative templates, end-to-end tooling, etc.

How to serve an Angular 7 application


on an Apache Web Server with Gzip
Compression

Ramya Balasubramanian

Aug 8, 2020·6 min read

An Angular application under development is served from local memory, using


webpack dev server. This webpack dev server provides a simple web server and the
ability of live reloading.

This story focusses on how you can serve the application from an Apache 2.4 web
server and also how you can optimise the bundle size of the application using Gzip
compression.

Lets first begin with Apache Http server installation on Windows OS.
1. Download the appropriate zip file
from https://www.apachelounge.com/download/ and unzip it into your C drive.It
looks like the screenshot below

apachelounge website

2. The unzipped httpd-2.4.46-win64-VS16 folder would contain an Apache folder with


the below files and folders. We shall be looking into
the Apache24/conf/httpd.conf file for making all server configurations.

The httpd.conf file is the main configuration file for the Apache web server
Apache24 folder contents
conf folder contents

Before we begin the installtion, lets take a peep into this httpd.conf file to check the
ServerRoot directive value.

The ServerRoot specifies the directory in which the configuration files of the Apache
server lives. It allows Apache to know where it can find its configuration files when it
starts.
Define SRVROOT “c:/Apache24”
ServerRoot “${SRVROOT}”

As you can see it is C://Apache24. Thus we must move the Apache24 folder out of the
the httpd-2.4.46-win64-VS16 folder into the C drive. This is essential for successful
installtion.

3. To install the Apache server, you can go to CMD,navigate to


the Apache24/bin folder and enter the below command.
httpd.exe -k install
4. Now lets check the Angular 7 application. Its a simple application
named ApacheAngular with just 2 components- Bootstrapped AppComponent and a
HomeComponent.
//Routing Definition
const routes: Routes = [{
path:’home’,
component:HomeComponent
}];@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Lets take a look at the angular.json file to check the build optimisation methods in


use. Below is a snippet of the architect.build section of the file.
“optimization”: true,
“outputHashing”: “all”,
“sourceMap”: false,
“extractCss”: true,
“namedChunks”: false,
“aot”: true,
“extractLicenses”: true,
“vendorChunk”: true,
“buildOptimizer”: true,

Below is a snippet of the scripts section of the package.json. Please note the use of —


prod flag in the ng build command. This greatly helps in keeping the bundle size to a
minimum value.
“scripts”: {
“ng”: “ng”,
“start”: “ng serve”,
“build”: “ng build — prod”,
“test”: “ng test”,
“lint”: “ng lint”,
“e2e”: “ng e2e”
},

If your application has multiple feature modues as well, please incorporate Lazy


Loading with Preloading Strategy to reduce the size of main.ts and for smaller
application start up time.
Now lets build this project by running the below command in the terminal.
npm run build

It creates a dist/ApacheAngular folder with all js,css,html files and other assets.

dist/ApacheAngular folder

5. Lets get back to the Apache server config. We need to achieve 2 tasks:

=>Serve the angular application from the Apache Server.

=>The Apache Server must compress the contents of the angular build before serving it
in the browser.
To achieve these tasks, we need to make a few changes to the
Apache24/conf/httpd.conf file.

1. The DocumentRoot is the directory out of which the angular application will be
served. This property’s value must be changed from
DocumentRoot “${SRVROOT}/htdocs”

To
DocumentRoot “D:/ApacheAngular/dist/ApacheAngular”

${SRVROOT} is the ServerRoot i.e C://Apache24 and htdocs is a folder within the
ServerRoot containing a default index.html file. This is the html file the Apache server
will render by default when the server starts.

We are changing it to the path of the dist folder containing the angular build
contents.We would like to render the index.html file in the dist folder.

2. Just after DocumentRoot,we have Directory tag which needs to be modified from
<Directory “${SRVROOT}/htdocs”>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

To
<Directory "D:/ApacheAngular/dist/ApacheAngular">
FallbackResource ./index.html
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

<Directory> and </Directory> are used to enclose a group of directives that will apply
only to the named directory, sub-directories of that directory, and the files within the
respective directories.
“D:/ApacheAngular/dist/ApacheAngular” is the path to the Directory.

FallbackResource directive defines a default URL for requests that don’t map to a


file.I shall explain the importance of FallbackResource directive later in the story.

Now lets start the Apache server and load Angular Application.

Make sure you are in the Apache24/bin folder in the CMD. Type the below
command:
httpd.exe -k start

Then hit localhost:80 in the browser. The port can be set to a value you choose by
modifying the below property in the httpd.conf file.
Listen 80
localhost:8080

Now when you hit localhost:80/home, the Apache server would have returned a
404 Not Found error incase the FallbackResource directive had not been set as below.
<Directory "D:/ApacheAngular/dist/ApacheAngular">
FallbackResource ./index.html
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

This directive ensures that the Apache server must route all requests to index.html. The
routing to the specific path /home is taken care by Angular.

The below screenshow shows the size of the js files before compression.

main.js -5.4KB,vendor.js is 278KB,index.html is 956B


Size of the files before compression

Now lets configure the apache server to compress the JS,CSS and HTML files before
rendering in the browser.

3. The AddOutputFilterType directive assigns an output filter to a particular media-


type.
AddOutputFilterByType DEFLATE text/html text/css application/x-javascript
application/javascript

DEFLATE is the filter which will compress all the files of the below media-types
before sending it to the client.

text/html text/css application/x-javascript application/javascript

Above code needs to be added under the <Directory> tag already mentioned before.
<Directory "D:/ApacheAngular/dist/ApacheAngular">
FallbackResource ./index.html
AddOutputFilterByType DEFLATE text/html text/css application/x-javascript
application/javascript
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
To enable the AddOutputFilterType directive and DEFLATE filter to work we need
to 2 load modules. In order to do that, we just need to uncomment(i.e remove the #)
below 2 lines in the beginning of httpd.conf file.
LoadModule deflate_module modules/mod_deflate.so
LoadModule filter_module modules/mod_filter.so

We need to restart the server for the above compression changes to take effect. Again
make sure you are in the Apache24/bin folder before entering the below command.
httpd.exe -k restart

Hit localhost:80 in the browser.

Now a very good question to ask is how do we know if the contents are actually
compressed?

Hit the Network tab of the browser and check the Content-Encoding in the response
headers. It will be set to gzip which proves that the contents are indeed compressed
and rendered by the server.
Response Headers

The compression also reduces the angular bundle size to a great extent.

vendor.js has reduced from 278KB to 75KB, main.js from 5.4 KB to 2.3KB,index.html
from 956B to 702B.

Size of files post compression

You can stop the Apache server by entering the below command
httpd.exe -k stop
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it(`should have as title 'sharedata'`, () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('sharedata');
  });

  it('should render title', () => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.nativeElement as HTMLElement;
    expect(compiled.querySelector('.content span')?.textContent).toContain('sharedata app is running!');
  });
});

You might also like