Google News
logo
Angular Interview Questions
  Angular is the platform that makes it easy to develop robust web applications. It unites the declarative templates, dependency injection, the end to end tooling and integrated the top perform to resolve the development challenges of developers. Angular authorizes developers to develop applications that could live on the web and mobile respectively.
 
  The framework, written in pure JavaScript, was intended to decouple an application’s logic from DOM manipulation, and aimed at dynamic page updates.
 
  It was aimed to help both developers and designers to build web applications by simply using the HTML tag. And it was officially released in 2010 by Google engineers.
 
  In 2010, this framework’s main benefit was, it let you turn HTML-based documents into dynamic content. It can synchronize data automatically with models and views. So, developing with Angular became easier and faster like never before.
 
  Thereafter Google has released various versions of Angular framework with the respective time frame. Currently, we have the Angular 9 and version 10 is in the pipeline.
Ivy in Angular version 8 is considered as the Rendering Engine. It was released in Angular 8 as Opt-in. It has opted as the code name for Angular’s next-generation rendering pipeline and compilation. By default, Ivy is intended to be the rendering engine in Angular 9
The key features of Angular 8 are as follows:
 
 a) Differential Loading to create two different production bundles of your app.

 b) New Dynamic Lazy Loading modules for imports.

 c) Supports Web Workers.

 d) Supports TypeScript version 3.4.

 e) Availability of New Workspace APIs and Builder.

 f) Bazel Support.

 g) Opt-In usage sharing.

 h) Ivy Rendering Engine: The new compiler for Angular version 8.
ngUpgrade improvements.
Bazel is one of the key features present in Angular version 8. It always allows you to build CLI applications quickly. Bazel is considered a built tool that is developed and mostly used by Google as it can build applications in any language. The entire Angular framework is built with Bazel. Moreover, Bazel allows you to break an application into different build units which are defined at the NgModule level.
Codelyzer in Angular version 8 is the open-source tool that is present on the top of the TSLint. The main purpose of Codelyzer is to verify whether the Angular TypeScript 3.4 projects are following the set of linting rules or not. It mainly focuses on the static code in Angular TypeScript. In simple words, we can say that the main purpose of the Codelyzer in Angular version 8 is to check the quality and correctness of the program.
The main purpose of the Wildcard Router in Angular version 8 is to match every URL as an instruction to get a clear client-generated view. This Wildcard route always comes last as it needs to perform its task at the end only. It is mainly used to define the route of the pages in Angular 8.
SPA means Single Page Applications. Such web applications load the HTML, CSS or JS of the page once, and don’t require reloading within page-to-page navigation.
 
Though being not an absolutely new solution, SPAs have been growing in popularity recently. Here are three main SPA Advantages.
 
1.Speed
 
On SPA, the page navigation seems to be quick enough thank to caching process. It means that an application will not load the whole page at the request of a user, it will only download the required parts.
 
2.Caching process
 
On the one hand, an application never stops checking if the previously downloaded data remains the same to update it when needed. So, the app doesn’t waste time loading the whole page again and again. On the other hand, the Multiple Page Application successfully uses caching as well, though the download speed here depends more on business needs and can be increased if necessary.
 
3.UX
 
UX design in SPA is generally better and more pleasant for an end-user. A great SPA advantage and the main reason for turning to SPA is its high interactivity and possibility to work offline. Thus, it seems that you’re dealing with a desktop application rather than with a web page.
 
So, Single Page Application built in Angular is quick to build and easy to use, though it possesses some cons as well as pros.

Metadata is used to decorate the class so that it can configure the expected behavior of a class. Decorators are the core concept when developing with Angular (versions 2 and above). The user can use metadata to a class to tell Angular app that AppComponent is the component. Metadata can be attached to the TypeScript using the decorator.

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

@Component is a decorator which makes use of configuration object to 
create the component and its view.
Decorator : A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
 
Directives : Angular Directive is basically a class with a @Directive decorator. A component is also a directive-with-a-template. A @Component decorator is actually a @Directive decorator extended with template-oriented features. Whenever Angular renders a directive, it changes the DOM according to the instructions given by the directive. The directive appears within an element tag similar to attributes.
Architecture : AngularJS uses MVC or Model-View-Controller architecture, where the Model contains the business logic, Controller processes information and View shows the information present in the Model.
Angular replaces controllers with Components. Components are nothing but directives with a predefined template.
 
Language : AngularJS uses JavaScript language, which is a dynamically typed language.
Angular uses TypeScript language, which is a statically typed language and is a superset of JavaScript. By using statically typed language, Angular provides better performance while developing larger applications.
 
Mobile Support : AngularJS does not provide mobile support.
Angular is supported by all popular mobile browsers.
 
Structure : While developing larger applications, the process of maintaining code becomes tedious in the case of AngularJS.
In the case of Angular, it is easier to maintain code for larger applications as it provides a better structure.
 
Expression Syntax : While developing an AngularJS application, a developer needs to remember the correct ng-directive for binding an event, or a property. Whereas in Angular, property binding is done using "[ ]" attribute and event binding is done using "( )" attribute.
Angular expressions are code snippets that are usually placed in binding such as {{ expression }} similar to JavaScript. These expressions are used to bind application data to HTML
Syntax: {{ expression }}
Scope in Angular is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in a hierarchical structure which mimics the DOM structure of the application. Scopes can watch expressions and propagate events.
A core feature of Angular, directives are attributes that allow you to write new HTML syntax, specific to your application. They are essentially functions that execute when the Angular compiler finds them in the DOM.  The Angular directives are segregated into 3 parts:
 
i)  Component Directives
ii) Structural Directives
iii) Attribute Directives
In Angular, data binding is one of the most powerful and important features that allow you to define the communication between the component and DOM(Document Object Model). It basically simplifies the process of defining interactive applications without having to worry about pushing and pulling data between your view or template and component. In Angular, there are four forms of data binding:
 
i)   String Interpolation
ii)  Property Binding
iii) Event Binding
iv) Two-Way Data Binding
A service() in Angular is a function that is used for the business layer of the application. It operates as a constructor function and is invoked once at the runtime using the ‘new’ keyword. Whereas factory() is a function which works similar to the service() but is much more powerful and flexible. factory() are design patterns which help in creating Objects.
The $scope objects in Angular are organized into a hierarchy and are majorly used by views. It contains a root scope which can further contain scopes known as child scopes. One root scope can contain more than one child scopes. Here each view has its own $scope thus the variables set by its view controller will remain hidden to the other controllers. The Scope hierarchy generally looks like:

Root $scope

$scope for Controller 1
$scope for Controller 2
..
$scope for Controller ‘n’
AOT stands for Angular Ahead-Of-Time compiler. It is used for pre-compiling the application components and along with their templates during the build process. Angular applications which are compiled with AOT has a smaller launching time. Also, components of these applications can execute immediately, without needing any client-side compilation.
jQlite is also known as jQuery lite is a subset of jQuery and contains all its features. It is packaged within Angular, by default. It helps Angular to manipulate the DOM in a way that is compatible cross-browser. jQLite basically implements only the most commonly needed functionality which results in having a small footprint.
Angular provides support to create custom directives for the following :
 
Element directives : Directive activates when a matching element is encountered.
Attribute : Directive activates when a matching attribute is encountered.
CSS : Directive activates when a matching CSS style is encountered.
Comment : Directive activates when a matching comment is encountered
Various filters are supported by Angular:
 
currency : Format a number to a currency format.
date : Format a date to a specified format.
filter : Select a subset of items from an array.
json : Format an object to a JSON string.
limit : To Limits an array/string, into a specified number of elements/characters.
lowercase : Format a string to lower case.
number : Format a number to a string.
orderBy : Orders an array by an expression.
uppercase : Format a string to upper case.
Dependency Injection (DI) is a software design pattern where the objects are passed as dependencies rather than hard-coding them within the component. The concept of Dependency Injection comes in handy when you are trying to separate the logic of object creation to that of its consumption. The ‘config’ operation makes use of DI that must be configured beforehand while the module gets loaded to retrieve the elements of the application. With this feature, a user can change dependencies as per his requirements.
Angular Events  are specific directives that help in customizing the behavior of various DOM events. Few of the events supported by Angular are listed below :
 
* ng-click
* ng-copy
* ng-cut
* ng-dblclick
* ng-keydown
* ng-keypress
* ng-keyup
* ng-mousedown
* ng-mouseenter
* ng-mouseleave
* ng-mousemove
* ng-mouseover
* ng-mouseup
* ng-blur
In Angular, a service is a substitutable object that is wired together using dependency injection. A service is created by registering it in the module it is going to be executed within. There are basically three ways in which you can create an angular service.
 
* Factory
* Service
* Provider
Compile : Compile function is used for template DOM Manipulation and to collect all the directives.
Link : Link function is used for registering DOM listeners as well as instance DOM manipulation and is executed once the template has been cloned.
Angular Global API is a combination of global JavaScript functions for performing various common tasks like:
 
* Comparing objects
* Iterating objects
* Converting data

There are some common Angular Global API functions like:
 
angular. lowercase : Converts a string to lowercase string.
angular. uppercase : Converts a string to uppercase string.
angular. isString : Returns true if the current reference is a string.
angular. isNumber : Returns true if the current reference is a number.
A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components.
 
Let's create a repoService which can be used across components,
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable({ // The Injectable decorator is required for dependency injection to work
  // providedIn option registers the service with a specific NgModule
  providedIn: 'root',  // This declares the service with the root app (AppModule)
})
export class RepoService{
  constructor(private http: Http){
  }

  fetchAll(){
    return this.http.get('https://api.github.com/repositories');
  }
}
The above service uses Http service as a dependency.
The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes.
 
Let's take a time observable which continuously updates the view for every 2 seconds with the current time.
@Component({
  selector: 'async-observable-pipe',
  template: `<div><code>observable|async</code>:
       Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
  time = new Observable(observer =>
    setInterval(() => observer.next(new Date().toString()), 2000)
  );
}
For using cookies in Angular, you need to include a  module called ngCookies angular-cookies.js.
 
To set Cookies – For setting the cookies in a key-value format ‘put’ method is used.
 
cookie.set('nameOfCookie',"cookieValue");

To get Cookies – For retrieving the cookies ‘get’ method is used.
 
cookie.get(‘nameOfCookie’);

To clear Cookies – For removing cookies ‘remove’ method is used.
 
cookie.delete(‘nameOfCookie’);
We use Angular ngFor directive in the template to display each item in the list. For example, here we iterate over list of users,
<li *ngFor="let user of users">
  {{ user }}
</li>
The user variable in the ngFor double-quoted instruction is a template input variable
Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding. It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property.
 
Let's take an example,
<h3>
  {{title}}
  <img src="{{url}}" style="height:50px">
</h3>
In the example above, Angular evaluates the title and url properties and fills in the blanks, first displaying a bold application title and then a URL.
You can update your view using any of the following:
 
ApplicationRef.prototype.tick() : It will perform change detection on the complete component tree.

NgZone.prototype.run() : It will perform the change detection on the entire component tree. Here, the run() under the hood will call the tick itself and then parameter will take the function before tick and executes it.

ChangeDetectorRef.prototype.detectChanges() : It will launch the change detection on the current component and its children.
You can chain pipes together in potentially useful combinations as per the needs. Let's take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below
import { Component } from '@angular/core';

        @Component({
          selector: 'app-birthday',
          template: `<p>Birthday is {{  birthday | date:'fullDate' | uppercase}} </p>` // THURSDAY, JUNE 18, 1987
        })
        export class BirthdayComponent {
          birthday = new Date(1987, 6, 18);
        }
A Pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
An Impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.
The response body doesn't may not return full response data because sometimes servers also return special headers or status code which which are important for the application workflow. Inorder to get full response, you should use observe option from HttpClient,
getUserResponse(): Observable<HttpResponse<User>> {
  return this.http.get<User>(
    this.userUrl, { observe: 'response' });
}
Now HttpClient.get() method returns an Observable of typed HttpResponse rather than just the JSON data.
ngOnInit() :  Is a lifecycle hook that is called after Angular has finished initializing all data-bound properties of a directive. It is defined as:
Interface OnInit {
 ngOnInit() : void
 }
MVVM Architecture removes tight coupling between each component. The MVVM architecture comprises of three parts:
 
* Model
* View
* ViewModel
 
The architecture allows the children to have reference through observables and not directly to their parents.
 
Model : It represents the data and the business logic of an application, or we may say it contains the structure of an entity. It consists of the business logic - local and remote data source, model classes, repository.

View : View is a visual layer of the application, and so consists of the UI Code(in Angular- HTML template of a component.). It sends the user action to the ViewModel but does not get the response back directly. It has to subscribe to the observables which ViewModel exposes to it to get the response.

ViewModel : It is an abstract layer of the application and acts as a bridge between the View and Model(business logic). It does not have any clue which View has to use it as it does not have a direct reference to the View. View and ViewModel are connected with data-binding so, any change in the View the ViewModel takes note and changes the data inside the Model. It interacts with the Model and exposes the observable that can be observed by the View.
If the request fails on the server or failed to reach the server due to network issues then HttpClient will return an error object instead of a successful reponse. In this case, you need to handle in the component by passing error object as a second callback to subscribe() method.
 
Let's see how it can be handled in the component with an example,
fetchUser() {
  this.userService.getProfile()
    .subscribe(
      (data: User) => this.userProfile = { ...data }, // success path
      error => this.error = error // error path
    );
}
RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables.
 
For example, you can import observables and operators for using HttpClient as below,
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
Transpiling is the process of converting the typescript into javascript (using Traceur, a JS compiler). Though typescript is used to write code in the Angular applications, the code is internally transpiled into javascript. 
When it comes to the communication of Angular Components, which are in Parent-Child Relationship; we use @Input in Child Component when we are passing data from Parent to Child Component and @Output is used in Child Component to receive an event from Child to Parent Component
ViewEncapsulation decides whether the styles defined in a component can affect the entire application or not. There are three ways to do this in Angular: 
 
Emulated : styles from other HTML spread to the component.
 
Native : styles from other HTML do not spread to the component.
 
None : styles defined in a component are visible to all components.
RouterOutlet is a substitution for templates rendering the components. In other words, it represents or renders the components on a template at a particular location.
With the existence of package.json, it will be easy to manage the dependencies of the project. If we are using typescript in the angular project then we can mention the typescript package and version of typescript in package.json.
Here‘s a simple class that is created with a greeting message which can be retrieved with the greet() function.
class Greeter {
  greeting: string;
     constructor(message: string) {
        this.greeting = message;
      }
       greet() {
         return "Hello, " + this.greeting;
       }
     }

  let greeter = new Greeter("world");
The constructor is a feature of the class itself, not Angular. The main difference is that Angular will launch ngOnInit after it has finished configuring the component. Meaning, it is a signal through which the @Input() and other banding properties and decorated properties are available in ngOnInit, but are not defined within the constructor by design.
Interceptor is just a fancy word for a function that receives requests/responses before they are processed/sent to the server. You should use interceptors if you want to pre-process many types of requests in one way. 
Change Detection is the process of synchronizing a model with a view. In Angular, the flow of information is unidirectional, even when using the ng Model to implement two-way binding, which is syntactic sugar on top of a unidirectional flow.
 
Change Detection Mechanism-moves only forward and never looks back, starting from the root (root) component to the last. This is the meaning of one-way data flow. The architecture of an Angular application is very simple — the tree of components. Each component points to a child, but the child does not point to a parent. One-way flow eliminates the need for a $digest loop.
Lazy loading of modules is needed to break the code into pieces. When downloading the app in the browser, it doesn’t load all of the application code. During the transition to the route with lazy loading, the module has to load the code into a browser.
 
Exemple for using lazy loading modules:
{ path: ‘example’, loadChildren: ‘./example/example.module#ExampleModule’, component: PublicComponent },
Some of them are :

* Avoid using/injecting dynamic HTML content to your component.

* If using external HTML which is coming from database or somewhere outside the application, sanitize it before using.

* Try not to put external urls in the application unless it is trusted. Avoid url re-direction unless it is trusted.

* Consider using AOT compilation or offline compilation.

* Try to prevent XSRF attack by restricting the api and use of the app for known or secure environment/browsers.
* Consider lazy loading instead of fully bundled app if the app size is more.

* Make sure that any 3rd party library, which is not used, is removed from the application.

* Have all dependencies and dev-dependencies are clearly separated.

* Make sure the application doesn’t have un-necessary import statements.

* Make sure the application is bundled, uglified, and tree shaking is done.

* Consider AOT compilation.
MergeMap essentially is a combination of mergeAll and map. MergeAll takes care of subscribing to the 'inner' Observable so that we no longer have to Subscribe two times as mergeAll merges the value of the 'inner' Observable into the 'outer' Observable.
Just like if and for in other languages, ngIf and ngFor are used as control statements. Example –
<p *ngIf="display">Show this only if the Boolean "display" is true</p>
Where the display is a boolean with the value true or false. Learn more about ngIf.
 
ngFor is used to loop through and display elements of an array (set of data).
<tr *ngFor="let student of students; let i = index"> <td>{{student.name}}

</td> <td>{{i}}</td> </tr>​
The second part (i=index) is optional and only needed if you want to display the index.
Digest cycle is the process of monitoring watchlist to track the changes in the value of the watch variable. The digest cycle is implicitly triggered, but we can also trigger it manually using $apply() function.
Yes, we can create custom pipes.
 
* Pipe metadata @Pipe decorator can be imported from core Angular library
* Pipe is a class that is decorated with the above metadata (@Pipe({name: 'myCustomPipe'}))
* The next step is to define the transformation. For this, the pipe class should implement the method transform() of the PipeTransform class.
* Specify the pipe name in the main code
<p>Size: {{number | myCustomPipe: 'Error'}}</p>
Angular has 8 lifecycle hooks and these are,
 
* ngOnInit() and ngOnDestroy() – called only once.
* ngAfterContentInit() and ngAfterViewInit() – Called after the projected content and view has been initialized.
* ngAfterContentChecked() and ngAfterViewChecked() – Called every time the projected content and view have been checked.
* ngOnChanges() – Called after @Input property changes. (Bounded input properties)
* ngDoCheck() – Called during all the change detection run.

All the above (onChanges, onInit, DoCheck etc..) should be imported from @angular/core.
Angular uses webpack module bundler to bundle the source codes and also helps to load the code chunks from server to browser.
A dumb component is not aware of what happens outside itself. It only receives input via property bindings and only emits output data as events.
 
Using smart and dumb components is a good practice. It greatly improves separation of concerns, making your application easier to understand and maintain. If your database or back-end API changes, you don’t have to worry about your dumb components. It also makes your dumb components more flexible, allowing you to reuse them more easily in different situations. If your application needs the same component twice, where one time it needs to write to a back-end database and another time it needs to write to an in-memory database, a dumb component allows you to accomplish exactly that.
Angular’s internal CookieXSRFStrategy and DomSanitizer classes are helping us to be safe XSS/CSRF/XSRF. 
 
DomSanitizer takes care of removing the dangerous bits in order to prevent an XSS attack.
 
CookieXSRFStrategy takes care of preventing CSRF/XSRF attacks.
 
CSRF/XSRF protection is enabled by default on the client but only works if the backend sets a cookie named XSRF-TOKEN with a random value when the user authenticates.
The following are the advantages of Angular 8, and they are as follows:
 
* Higher performance
* Effective clean code development
* debugging templates
* Angular 8 supports multiple apps in a single domain.
* easier implementation.
NgModules in Angular version 8 varies from other JavaScript modules. Each and every Angular app has at least one module called AppModule. The NgModule provides a bootstrap mechanism to launch different applications. Commonly, every Angular App contains many functional modules to do things. The key features of Angular 8 modules are as follows:
 
Own functionality of the NgModule can be exported and can also be used by other NgModules.
Angular 8 NgModule can import functionalities from other NgModules.
Class decorators appear just before class definition, whereas class field decorators appear just before a field in the class definition. Examples of class decorators are @Component, @NgModule etc… Examples of a class field decorator are @Input, @Output etc…
The double curly braces represent interpolation. It is a special syntax. Angular converts it into property binding. You can think of it as an alternate for property binding. The name of the component is written inside the inner curly braces. During execution, the name is replaced by the actual string value of the property. For example,
 
<h2> {{apptitle}} <img src="{{imgname}}" style="height:30px"> </h2> 
 
Angular will evaluate and replace apptitle and imgname with their actual values.
This is a representation for ngModel used for two-way data binding. It is written as [(ngModel)] = “propertyvalue”.
The root module that you bootstrap to launch the application is called as a bootstrapping module. Every Angular application has a bootstrapping module. It is also called as the AppModule. The bootstrapping module is mentioned in the AppModule class.
 
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
With JIT, the compilation happens during run-time in the browser. It is the default way used by Angular. The commands used for JIT compilation are –
ng build ng serve 
 
In AOT compilation, the compiler compiles the code during the build itself. The CLI command for aot compilation is -
ng build --aot ng server –aot
 
AOT is more suitable for the production environment whereas JIT is much suited for local development.
The components, framework and CLI used by Angular applications are packaged as npm packages. Npm packages can be downloaded using the npm CLI client.
Angular JavaScript framework launched for the first time in 2009, the latest version of AngularJS is Angular 9 and it is launched on February 6th, 2020. Angular is one of the best and most popular frameworks and widely used for developing front-end desktop web applications or single-page applications by Angular JS Development Company.
 
Furthermore, Angular is the first choice for the front-end development for developers across the world. The new version of Angular is released every six months. In this blog, we shall overview the new features of version 9.

Angular 9 : Features
* Default Ivy Compiler
* Smaller Bundle Size
* Better Debugging
* Faster Compilation
* Ahead-of-time (AOT)
* Angular 9 requires Typescript 3.7


Angular 9’s compiling and rendering engine is known as Ivy. The older versions of Angular made use of View Engine. The bundle size produced by the View Engine is very large but with Ivy, this bundle has considerably reduced thereby helping Angular overcome its bundle issues.
 
For example, the simplest Hello World program was about 36Kb which is quite a large bundle size for a simple Hello World program. So, the Angular team decided that they will keep a threshold value of 10Kb. This was called the cake threshold because the head of that team decided to give the team all the cake in case they reduce the bundle size to below 10Kb.

The team was successful in reducing the bundle size incredibly to just 7.3Kb with the minified Ivy version and something even better i.e 2.7Kb with the Ivy Compressed version. This was indeed a great achievement and they did deserve all the cake!
 
Benefits of Using Ivy :
* Smaller bundle size
* Very helpful when it comes to debugging
* Brings faster compilation
To understand how Ivy reduces the bundle size, you will first need to understand how the View Engine works. When you compile any of your components using the View Engine, say for instance example.component, you basically get two JavaScript files. They are the example.component.js file which consists of the compiled TypeScript code and example.component.ngfactory.js file which is a static representation of the template code. So here, there will be a mapping of these two files which consumes a much longer build time.
 
So, the Angular team decided that the second file, i.e the .ngfactory.js file, can be removed by just adding the template code within the JavaScript code itself. The Ivy makes use of function calls rather than iterating over each element as in the View Engine.
First, update to the latest version of 8
ng update @angular/cli@8 @angular/core@8
Then, update to 9
ng update @angular/cli @angular/core
The main goal of Angular 9 is to make it available for all applications. The main benefits of Ivy is to reduce the size of applications for better user experience.
An Angular application consists mainly of components and their HTML templates. Because the components and templates provided by Angular cannot be understood by the browser directly, Angular applications require a compilation process before they can run in a browser.
 
The Angular ahead-of-time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the browser.
 
This guide explains how to specify metadata and apply available compiler options to compile your applications efficiently using the AOT compiler.
 
Here are some reasons you might want to use AOT.

Reasons Details
Faster rendering With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the application first.
Fewer asynchronous requests The compiler inlines external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files.
Smaller Angular framework download size There's no need to download the Angular compiler if the application is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.
Detect template errors earlier The AOT compiler detects and reports template binding errors during the build step before users can see them.
Better security AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks.

Choosing a compiler

Angular offers two ways to compile your application :

Angular compile Details
Just-in-Time (JIT) Compiles your application in the browser at runtime. This was the default until Angular 8.
Ahead-of-Time (AOT) Compiles your application and libraries at build time. This is the default starting in Angular 9.

When you run the ng build (build only) or ng serve (build and serve locally) CLI commands, the type of compilation (JIT or AOT) depends on the value of the aot property in your build configuration specified in angular.json. By default, aot is set to true for new CLI applications.
The Angular AOT compiler extracts metadata to interpret the parts of the application that Angular is supposed to manage. You can specify the metadata explicitly in decorators such as @Component() and @Input(), or implicitly in the constructor declarations of the decorated classes. The metadata tells Angular how to construct instances of your application classes and interact with them at runtime.
 
In the following example, the @Component() metadata object and the class constructor tell Angular how to create and display an instance of TypicalComponent.
@Component({
  selector: 'app-typical',
  template: '<div>A typical component for {{data.name}}</div>'
})
export class TypicalComponent {
  @Input() data: TypicalData;
  constructor(private someService: SomeService) { … }
}
The Angular compiler extracts the metadata once and generates a factory for TypicalComponent. When it needs to create a TypicalComponent instance, Angular calls the factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency.

Compilation phases  :  There are three phases of AOT compilation.

  Phase Details
1 code analysis In this phase, the TypeScript compiler and AOT collector create a representation of the source. The collector does not attempt to interpret the metadata it collects. It represents the metadata as best it can and records errors when it detects a metadata syntax violation.
2 code generation In this phase, the compiler's StaticReflector interprets the metadata collected in phase 1, performs additional validation of the metadata, and throws an error if it detects a metadata restriction violation.
3 template type checking In this optional phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates. You can enable this phase explicitly by setting the fullTemplateTypeCheck configuration option; see Angular compiler options.

Metadata restrictions :  You write metadata in a subset of TypeScript that must conform to the following general constraints:
 
* Limit expression syntax to the supported subset of JavaScript
* Only reference exported symbols after code folding
* Only call functions supported by the compiler
* Decorated and data-bound class members must be public
73 .
What is the Just in Time (JIT) compiler ?
Just in time compiler provides compilation during the execution of the program at a run time before execution. In simple words, code get compiles when it’s needed, not at the build time.
Just in time compiler compiles each file separately and it’s mostly compiled in the browser. You don’t have to build your project again after changing your code.

Most compiling is done on the browser side, so it will take less compiling time.

If you have a big project or a situation where some of your components don’t come in use most of the time then you should use the Just in time compiler.

Just in Time compiler is best when your application is in local development.
Initially, compiler was responsible for converting a high-level language into machine language, which would then be converted into executable code.
 
Just in time compiler, compiles code at runtime which means instead of interpreting byte code at build time, it will compile byte code when that component is called.
 
A few important points :
 
* In case of Just in time, not all code is compiled at the initial time. Only necessary component which are going to be needed at the starting of your application will be compiled. Then if the functionality is need in your project and it’s not in compiled code, that function or component will be compiled.

* This process will help to reduce the burden on the CPU and make your app render fast.

* One more interesting thing is, you can see and link to your source code in inspect mode because Just in Time, compiles your code with JIT mode and a map file.
JIT AOT
JIT downloads the compiler and compiles code exactly before Displaying in the browser. AOT has already complied with the code while building your application, so it doesn’t have to compile at runtime.
Loading in JIT is slower than the AOT because it needs to compile your application at runtime. Loading in AOT is much quicker than the JIT because it already has compiled your code at build time.
JIT is more suitable for development mode. AOT is much suitable in the case of Production mode.
Bundle size is higher compare to AOT. Bundle size optimized in AOT, in results AOT bundle size is half the size of JIT bundles.

You can run your app in JIT with this command:

ng build OR ng serve

To run your app in AOT you have to provide –aot at the end like:

ng build --aot OR ng serve --aot  
You can catch template binding error at display time. You can catch the template error at building your application.
Let's see what Angular 10 is, what's new in Angular 10, and the new features and breaking changes the Google-developed web framework Angular 10 has introduced to us :
 
* New Date Range Picker
* Warnings about CommonJS imports
* Optional Stricter Settings
* Keeping Up to Date with the Ecosystem
* New Default Browser Configuration
* Deprecations and Removals
The comparison of Angular 11 vs Angular 12 vs Angular 13, we learned about breaking changes, performance, and core structural changes, as well as several additional deprecations and upgrades. Let’s have a look at a table that compares the features offered by each :

Angular v11 Angular v12 Angular v13
TypeScript 4.0 TypeScript 4.2 TypeScript 4.4
Webpack 5 Support Webpack 5.37 Support Webpack 5.37 Support
Migration to ESLint Migrating from legacy i18n message IDs View Engine is no longer available
Deprecation of IE 9, 10, and IE mobile Deprecating support for IE 11 End of IE 11 support
Updates on Operation Byelog Improved component tests harness Improvements to the Angular CLI
Updated Language Service Preview Updated Language Service Preview Improvements to Angular tests
Strict checks with a flag Default strict mode Framework changes and dependency updates
Roadmap to provide early feedback Roadmap to inform about the priorities of the Angular team Support to Adobe Fonts
Linting Migration to default IVY-based language service Changes to the Angular Package Format (APF)
Improved Ngcc compiler Improved logging and reporting PR merges from community
Updated Hot Module Replacement (HMR) Support HTTP improvements Component API updates
Angular 14 could be installed via npm using the next flag.
 
Simply open a new command line interface and run the following command to install the latest version of Angular:
npm install --global @angular/cli@next
This will install the latest version of Angular CLI globally on your development machine.
 
Check the angular CLI version using below command
ng version
Before Updating : 
There aren't currently any changes needed before moving between these versions.

During the Update : 
* Run ng update @angular/core@14 @angular/cli@14 which should bring you to version 14 of Angular.

* Angular now uses TypeScript 4.6, read more about any potential breaking changes: https://devblogs.microsoft.com/typescript/announcing-typescript-4-6/

* Make sure you are using Node 14.15.0 or later

* Form models now require a generic type parameter. For gradual migration you can opt-out using the untyped version of the form model classes.

* Remove aotSummaries from TestBed since Angular no longer needs them in Ivy.

* Remove headers from JSONP requests. JSONP does not supports headers and if specified the HTTP module will now throw an error rather than ignoring them.

* Resolvers now will take the first emitted value by an observable and after that proceed to navigation to better align with other guards rather than taking the last emitted value.

* Update initialNavigation: 'enabled' to initialNavigation: 'enabledBlocking'.

* If you are defining routes with pathMatch, you may have to cast it to Route or Routes explicitly. Route.pathMatch is no longer compatible with string type.

* The promise returned by LoadChildrenCallback now has a stricter type parameter Type<any>|NgModuleFactory<any> rather than any.

* The router does no longer schedule redirect navigation within a setTimeout. Make sure your tests do not rely on this behavior.

* Implementing the LocationStrategy interface now requires definition of getState().

* Sending + as part of a query no longer requires workarounds since + no longer sends a space.

* Implementing AnimationDriver now requires the getParentElement method.

* Invalid route configurations of lazy-loaded modules will now throw an error rather than being ignored.

* Remove the resolver from RouterOutletContract.activateWith function and the resolver from OutletContext class since factory resolvers are no longer needed.

* Router.initialUrl accepts only UrlTree to prevent a misuse of the API by assigning a string value.

After the Update
There aren't currently any changes needed after moving between these versions.

Source : angular
Angular 14, the latest version of the TypeScript-based free and open-source web app framework was launched on 2nd June 2022. Considering all the releases before, Angular 14 is one of Angular's most methodical pre-planned upgrades. If you are interested in a bird-eye view of what's fresh in Angular 14, then here's a quick sneak at latest Angular 14 features and updates. 
 
Angular 14 Features :
 
* Standalone Components
* Typed Forms
* Streamlined page title accessibility (Title Strategy)
* Extended developer diagnostics (ng compilation) 
* Bind to protected component members
* Optional Injectors in Embedded Views
* NgModel OnPush

Source : F T L

In the latest version of Angular, you can write dynamic CSS styles by using the Angular styling system, which includes features such as component-level styles, template-level styles, and dynamic styles.
 
Component-level styles : You can add styles to a component by creating a styles property in the @Component decorator and specifying an array of CSS files or a string of CSS code. These styles will only be applied to the component they are associated with.
 
Template-level styles : You can add styles directly to a template by using the "style" or "styleUrls" properties in the template tag.
 
Dynamic styles : You can use Angular's template expressions and template statements to create dynamic styles. For example, you can use ngStyle and ngClass directives to bind styles and classes to a component based on conditionals.
 
It is recommended to use the component-level styles when possible, as they provide better performance and a clear structure.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div [ngStyle]="{'color': myColor}">Hello World!</div>
  `,
  styles: [`
    div {
      font-size: 20px;
    }
  `]
})
export class AppComponent {
  myColor = 'blue';
}
In this example, the color of the "div" element will change to blue, by using ngStyle.
Writing unit tests in Angular involves creating test cases for individual components, services, directives, and pipes. Here's an overview of how to write a unit test in Angular :

* Create a new test file : For each component, service, directive, or pipe you want to test, create a new file with the ".spec.ts" extension. For example, if you have a component named "MyComponent", create a new file named "my.component.spec.ts".

* Import necessary dependencies : In the test file, import the dependencies needed for testing the component, service, directive, or pipe. For example, if you're testing a component that uses the HttpClient service, you would import the HttpClientModule.

* Create the test suite : Use the describe() function to create the test suite. The first argument is a string that describes what is being tested, and the second argument is a function that contains the tests.

* Write the tests : Use the it() function to write individual tests. The first argument is a string that describes the test, and the second argument is a function that contains the test code.

* Use appropriate testing functions : Angular provides a number of testing functions to help test components, services, directives, and pipes. For example, the TestBed.createComponent() function creates a new instance of a component for testing.

* Use appropriate matchers : Angular also provides a number of matchers to help check the output of your tests. For example, the expect().toEqual() matcher checks that the actual value is equal to the expected value.

* Run the tests : Use the ng test command to run the tests.

Here's an example of a simple test for a component named "MyComponent":
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    });

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  });

  it('should create the component', () => {
    expect(component).toBeTruthy();
  });
});


In this example, we import the necessary testing dependencies, create a new test suite using the describe() function, create a new instance of the component using the TestBed.createComponent() function, and write a simple test using the expect().toBeTruthy() matcher to check that the component was created successfully.

Advertisement