What is Angular?

Angular is a client side framework, which is used to create web applications. The framework provides skeleton of the project and specifies clear guidelines, where to write which type of code.

Angular can be used in combination with any server side platform such as Java, NodeJS, Asp.Net, PHP, Python etc.

Angular is mainly used to create “data bindings”. That means, we establish relation between a variable and html element; When the value of the variable is changed, the same will be automatically effected in the corresponding html element; and vice versa. So that the developer need not write any code for DOM(Document Object Model) manipulations (updating values of html tags, based on user requirements.

for example, updating the list of categories when a new category added by the user). Thus the developer can fully concentrate on the application logic, instead of writing huge code for DOM manipulations. So we can achieve clean separation between “application logic” and “DOM manipulations”.

Angular mainly works based on “Components”. The component is a class, which represents a specific section (part) of the web page.

Goals of Angular ?

  • Separation of DOM manipulation from application logic.
  • Separation of HTML logic from application logic.
  • Make SPA (Single Page Application) development easier. SPA provides client-side navigation system; but can communicate with server only through AJAX; the web page never gets refreshed fully. Ex: Gmail.
  • Separation of business logic from application logic.
  • Enable Unit testing. The components can be unit tested individually.

Angular Vs AngularJS

Let’s have a quick look at the differences, which would be easier for you to upgrade.

#1) Programming Language

Angular 1 used JavaScript to build the application.

However, as an upgrade to Angular 1, Angular 2 uses TypeScript which is a superset of JavaScript and helps in building more structures and robust code.

#2) Architecture

While AngularJS is based on MVC (model-view-controller) design, Angular utilizes services/controller. Thus, if you are upgrading from Angular 1 to Angular 2, there is a possibility that you have to rewrite the whole code.

In Angular 4, the bundle’s size is further reduced by 60%, thereby helping in accelerated application development.

Model View Controller And Services Controller

AngularJS MVC
Angularjs Service Controller

#3) Syntax

In AngularJS you have to remember the right ngdirective to bind an image/property or an event.

However, Angular (2 & 4) focus on “()” for event binding and “[]” for property binding.

#4) Mobile Support

AngularJS was introduced without any inbuilt support for mobile application development. However, Angular offers support for building native mobile applications, which is something similar to what React Native offers.

#5) SEO Optimized

For developing SEO optimized applications in AngularJS, rendering of the HTML at the server side was required. This problem has been eliminated in Angular 2 and Angular 4.

#6) Performance

In specific, AngularJS is for designers. It does not offer much for the developers to play with.

However, Angular has many components to support a developer’s requirement, hence it can improve the overall performance of the application, especially in speed and dependency injection.

#7) Animation Package

When AngularJS was introduced, the code required for animation was always included in the application, whether or not required. But in Angular 4, the animation is a separate package which eliminates the necessity of downloading bundles of large files.


Animation Package-Angular JS

Angular 4

Angular 4

Top 10 New Features Of Angular 9

Default Ivy compiler

To top it all, the IVY compiler in Angular 9 fixes several bugs and has additional features to it as well

  • Improves the bundle sizes
  • Faster mobile apps
  • Allows for better debugging
  • Adds improved type checking
  • Faster Testing
  • New options for ‘providedIn’
  • IDE and language service improvements
  • Typescript 3.7 Support

Future of Angular 9

The main benefit of Ivy is to reduce the size of applications for better user experience.
Developers also now have clear insight into the syntax and the project structure.

In the opt-in preview, you can expect:

  1. Generated code that is easier to read and debug at runtime
  2. Faster re-build time
  3. Improved payload size (Real world applications should see some size improvements, but many more improvements are planned)
  4. Improved template type checking
  5. Great backwards compatibility

What is TypeScript

  • TypeScript is a programming language, which is developed based on JavaScript.
  • TypeScript is a superset of JavaScript, which adds data types, classes, interfaces and other features.
  • TypeScript = JavaScript + Data Types + Classes + Interfaces + Misc. Concepts (Arrow Functions + Multiline Strings + String Interpolation + Destructuring + Modules etc.)
  • TypeScript is built on the top of JavaScript. That means all the code of JavaScrpt works as-it-is in TypeScript, but in TypeScript, we can additionally use data types, classes, interfaces etc., concepts.
  • TypeScript is developed by Microsoft Corporation in 2012.

Build block Of Angular /Component Of Angular

Difference between TypeScript and JavaScript:

  • TypesScript is known as Object oriented programming language whereas JavaScript is a scripting language.
  • TypeScript has a feature known as Static typing but JavaScript does not have this feature.
  • TypeScript gives support for modules whereas JavaScript does not support modules.
  • TypeScript has Interface but JavaScript does not have Interface.

Advantages of using TypeScript over JavaScript 

  • TypeScript always point out the compilation errors at the time of development only. Because of this at the run-time the chance of getting errors are very less whereas JavaScript is an interpreted language.
  • TypeScript has a feature which is strongly-typed or supports static typing. That means Static typing allows for checking type correctness at compile time. This is not available in JavaScript.
  • TypeScript is nothing but JavaScript and some additional features i.e. ES6 features. It may not be supported in your target browser but TypeScript compiler can compile the .ts files into ES3,ES4 and ES5 also.

Disadvantages of using TypeScript over JavaScript

  • Generally TypeScript takes time to compile the code.

What are some of the advantages of Angular over other frameworks?

Features that are provided out of the box – Angular provides a number of built-in features like,routing, state management, rxjs library and http services straight out of the box. This means that one does not need to look for the above stated features separately. They are all provided with angular.
Declarative UI – Angular uses HTML to render the UI of an application. HTML is a declarative language and is much easier to use than JavaScript.
Long-term Google support – Google announced Long-term support for Angular. This means that Google plans to stick with Angular and further scale up its ecosystem.

What is directive in angular

Changes the appearance or behavior of a DOM element.

Types of directives

There are four types of directives in Angular,- SACC

  • Components directives
  • Structural directives
  • Attribute directives
  • Custom Directive

Structural Directive

The structural directive is used to add or remove the HTML Element in the Dom Layout, typically by adding, removing, or manipulating elements…
Its built-in types are *NgIf,*NgFor,*NgSwitch.
Structural directives are easy to recognize by using an asterisk (*).

Attribute Directive

Attribute directive is used to change/modify  the appearance or behavior of the HTML element in the Dom Layout.
Its built-in type is NgStyle, NgClass. it is used to change the attributes of the existing HTML element.
NgClass, NgStyle are the most used attribute directives.

Components directives

It is mainly used to specify the HTML templates. It is the most commonly-used directive in an Angular project. It is decorated with the @component decorator.
This directive is a class .The component directive is used to specify the template/HTML for the Dom Layout. Its built-in is @component.

  • app.component.css: contains all the CSS styles for the component
  • app.component.html: contains all the HTML code used by the component to display itself
  • app.component.ts: contains all the code used by the component to control its behavior

You can also find the app.module.ts file, which is used to define an Angular module.

Custom Attribute

We can create custom attribute directives and custom structural directives using a @Directive decorator. Using custom attribute directive we can change appearances such as text color, background color and font size of the body of an HTML element that can be called host element. To change appearance angular provides ElementRef class that can directly access DOM.

Benefits of using custom directive:

It is vulnerable to XSS(cross-site scripting) attacks when we directly use ElementRef in our application. It is better to create a custom directive and use ElementRef inside directive to change appearance or behavior of the host element.

Steps to be followed to create custom attribute directive

  1. Create a class decorated with @Directive.
  2. Assign the attribute directive name to the selector metadata of @Directive decorator.
  3. Use ElementRef class to access DOM to change host element appearance and behavior.
  4. Use @Input() decorator to accept user input in our custom directive.
  5. Use @HostListener() decorator to listen to events in custom attribute directive.
  6. Configure custom attribute directive class in application module in the declarations metadata of @NgModule.

Steps to be followed for customization of project structure and code

Create a folder under app called directives. Under directives create a file called red.directive.ts.

Code Ref. ofred.directive.ts

  1. import { DirectiveElementRef } from ‘@angular/core’;  
  3. @Directive({   
  4.      selector: ‘[myRed]’   
  5. })  
  6. export class MyRedDirective {  
  7.     constructor(elRef: ElementRef) {  
  8. = ‘red’;  
  9.     }  
  10. } —————————————————html template ———–
  11. body>    
  12.   <p myRed>Custom Attribute Directive By MJ</p>   
  13. </body>    

What is npm? node package manager

->npm is the world’s largest Software Library (Registry)
->npm is also a software Package Manager and Installer
->You can download all npm public software packages without any registration or logon.

npm includes a CLI (Command Line Client) that can be used to download and install software

npm is installed with Node.js

This means that you have to install Node.js to get npm installed on your computer.

All npm packages are defined in files called package.json.

The content of package.json must be written in JSON.

At least two fields must be present in the definition file: name and version.


The node_modules folder contains libraries downloaded from npm. You shouldn’t push it to github (you should even add it to your .gitignore), because everyone who clones your repository can download it themselves (based on your package.json).

Package.json VS package-lock.json

 the versioning file i.e. package.json.

It is used to install different open source and other available packages (that is, pre-packaged code modules) in a Node.js project. 

NPM version 5 introduced package-lock.json as a mechanism to capture the exact dependency tree installed at any point in time.

This helps with collaboration across different environments in which you want everyone fetching dependencies for a specific version of your project to fetch the same tree.

package.json defines the required dependencies and their respective versions using semantic versioning. However, semantic versioning can be tricky.

Module vs. component

A module in Angular is something which is made from components, directives , services etc. One or many modules combines up to make an Application.

Now Components in Angular are classes where you write your logic for the page you want to display.

Consider an example ,

You have to create an application for College Management . You divide your project into multiple parts like Admin, Students, Staff etc. These are modules.
Now in one of the module like Admin, you will have Add, Delete, Update User Info. These will be Components that will combine up and create a module.


A component in Angular is a piece of the Application with an associated template. It has a selector and will (usually) render the template, where ever the selector-tag is located.

A module instead is a collection of components, directives, pipes and so on.
Usually it is used to collect multiple small parts which belong to one bigger logical part.

For example, if we have a `DatePickerComponent` and a `TimePickerComponent`, they both may be included in a module `PickerModule`.

One important thing:

Each component can use other components, which are declared in the same module. To use components declared in other modules, they need to be exported from this module and the module needs to be imported.

Explain importance of Angular CLI ?

Angular CLI is a command-line interface (CLI) to automate your development workflow. It allows you to:

  • create a new Angular application
  • run a development server with LiveReload support to preview your application during development
  • add features to your existing Angular application
  • run your application’s unit tests
  • run your application’s end-to-end (E2E) tests
  • build your application for deployment to production.

To install Angular CLI, run:

$ npm install -g @angular/cli

This will install the ng command globally on your system.

To verify whether your installation completed successfully, you can run this:

$ ng version
  • ng init: create a new application in the current directory
  • ng new: create a new directory and run ng init inside the new directory.

So ng new is similar to ng init, except that it also creates a directory for you.

Assuming you haven’t created a directory yet, let’s use ng new to create a new project:

$ ng new my-app
  • ng g cl my-new-class: add a class to your application
  • ng g c my-new-component: add a component to your application
  • ng g d my-new-directive: add a directive to your application
  • ng g e my-new-enum: add an enum to your application
  • ng g m my-new-module: add a module to your application
  • ng g p my-new-pipe: add a pipe to your application
  • ng g s my-new-service: add a service to your application.

What is a decorator in Angular ?

The whole purpose of Angular decorators is to store metadata about a class, method, or property ,value etc. and decorators are going to be invoked at runtime.
When you configure a component, you are providing a metadata for that class that tells Angular that you have a component, and that component has a specific configuration.
Decorators are the features of Typescript and are implemented as functions. The name of the decorator starts with @ symbol following by brackets and arguments. That means in angular whenever you find something which is prefixed by @ symbol, then you need to consider it as a decorator

Commonly used Decorators:

There are many built-in decorators are available in angular. Some of them are as follows:

  1. @NgModule to define a module.
  2. @Component to define components.
  3. @Injectable to define services.
  4. @Input and @Output to define properties, etc.
Types of Decorators in Angular:

In Angular, the Decorators are classified into 4 types. They are as follows:- C-2PM

  1. Class Decorators: @Component and @NgModule
  2. Property Decorators: @Input and @Output (These two decorators are used inside a class)
  3. Method Decorators: @HostListener (This decorator is used for methods inside a class like a click, mouse hover, etc.)
  4. Parameter Decorators: @Inject (This decorator is used inside class constructor).

Note: In Angular, each decorator has a unique role.

Explain the types of Data bindings in Angular

Data Binding is a process that creates a connection to communicate and synchronize between the user interface and the data. In order words, we can say that Data Binding means to interact with the data and view. So, the interaction between the templates (View) and the business logic is called data binding.

What is Data Binding in Angular Application?
Types of Data Binding in Angular:

There are two types of Data binding available. They are as follows

  1. One-way Data Binding- where a change in the state affects the view (i.e. From Component to View Template) or change in the view affects the state (From View Template to Component).
  2. Two-way Data Binding- where a change from the view can also change the model and similarly change in the model can also change in the view (From Component to View Template and also From View template to Component).

In order to understand this better and remember, please have a look at the following image which describes the classification of Data Binding.

Types of Data Binding in Angular Application
Examples of Angular Data Bindings:
  1. Interpolation
  2. Property Binding
  3. Attribute Binding
  4. Class Binding
  5. Style Binding
  6. Event Binding
  7. Two-way binding

If you want to display the read-only data on a view template (i.e. From Component to the View Template), then you can use the one-way data binding technique i.e. the Angular interpolation.

The Interpolation in Angular allows you to place the component property name in the view template, enclosed in double curly braces i.e. {{propertyName}}

Property Binding?

The Property Binding in Angular Application is used to bind the values of component or model properties to the HTML element. Depending on the values, it will change the existing behavior of the HTML element. The syntax to use property is: [property] = ‘expression’

span[innerHTML] = ‘FirstName’.

Here, innerHTML is the target that is a property of span tag and FirstName is the source that is the component property.

How to use the Property Binding in Angular Application?
Angular Interpolation VS Property Binding:
Difference between Property Binding and Angular Interpolation?

Interpolation in Angular is just an alternative approach for property binding. It is a special type of syntax that converts into a property binding. 

But there are some scenarios where we need to use interpolation instead of property binding. For example, if you want to concatenate strings then you need to use angular interpolation instead of property binding as shown in the below image.

What is the difference between Angular Interpolation and Property Binding?

Working with non-string (Boolean) data:

When you are working with non-string values like Boolean to set the property value of an HTML element, then you need to use property binding instead of interpolation. For example, if you want to disable a button click event, then you need to set the disabled property of the button element using the property binding as shown in the below code.

Interpolation with Boolean data:

Please modify the app.component.ts file as shown below to use angular interpolation to set the disabled property of the button element. Here, we set the property value to false.
With the above changes in place, irrespective of the IsDisabledClick property value of the component class, the button is always disabled. Here we set the IsDisabled property value as false but when you run the application, it will not allow the button to be clickable.

Providing Security to Malicious Content

From the security point of view, both Angular data binding and Angular Interpolation protect us from malicious HTML content before rendering it on the web browser. Let us understand this with an example. In the following example, we are using angular interpolation to bind the malicious <script> tag.

Now, when we run the application, the Angular interpolation sanitizes the malicious content and displays the following in the browser.

How to use Property Binding in Angular Application?
In the below example we are using property binding. 

The Property Binding handles the malicious HTML content in a slightly different manner and when you run the application, you will get the following output in the browser. But the most important point that you need to keep in mind is, both property binding and interpolation protect us from malicious HTML content.

Providing Security to Malicious Content

HTML Attribute VS DOM Property with Example

The DOM stands for Document Object Model. When a browser loads a web page, then the browser creates the Document Object Model (DOM) for that page.

So in simple words, we can say that the DOM is an application programming interface (API) for the HTML, and we can use the programming languages like JavaScript or JavaScript frameworks like Angular to access and manipulate the HTML using their corresponding DOM objects.

In other words, we can say that the DOM contains the HTML elements as objects, their properties, methods, and events and it is a standard for accessing, modifying, adding or deleting HTML elements

Interpolation example: <button disabled='{{IsDisabled}}’>Click Me</button>
Property binding example: <button [disabled]=’IsDisabled’>Click Me</button>

If you look at the above two examples, you may feel that you are binding to the Button’s disabled attribute, but that is not true. You are actually binding to the disabled property of the button objectSo, the Angular data-binding is all about binding to the DOM object properties and not the HTML element attributes.

What is the difference between the HTML element attribute and DOM property?
  1. The Attributes are defined by HTML whereas the properties are defined by the DOM.
  2. The attribute’s main role is to initializes the DOM properties. So, once the DOM initialization complete, the attributes job is done.
  3. Property values can change, whereas the attribute values can never be changed.

Attribute Binding

In our Angular Interpolation and Property Binding articles, we discussed that they both (Interpolation and Property Binding) are dealing with the DOM Properties but not with the HTML attributes. But there are some HTML elements (such as colspan, area, etc) that do not have the DOM Properties.
Now the question is how to deal with such elements that do not have DOM Properties as we can’t use Interpolation and Attribute Binding. The Answer is Angular Attribute Binding.

With Attribute Binding in Angular, you can set the value of an HTML Element Attribute directly. So, the Attribute Binding is used to bind the attribute of an element with the properties of a component dynamically. 

Class Binding?

The Angular Class Binding is basically used to add or remove classes to and from the HTML elements. It is also possible in Angular to add CSS Classes conditionally to an element, which will create the dynamically styled elements and this is possible because of Angular Class Binding.

Style Binding?

The Angular Style Binging is basically used to set the style in HTML elements. You can use both inline as well as Style Binding to set the style in the element in Angular Applications. Here, in this article, I will show how to use both inline as well as style binding to style the HTML Elements with examples.

Two Way Binding?

The most popular and widely used data binding mechanism in Angular Application is two-way data binding. The two-way data binding is basically used in the input type filed or any form element where the user type or provide any value or change any control value on the one side and on the other side, the same automatically updated into the component variables and vice-versa is also true.

Angular Two Way Data Binding

The two-way data binding in Angular is actually a combination of Property Binding and Event Binding. The Syntax is given below:

<input [value] = ‘data 1’ (input) = ‘data = $’>

<input [(ngModel)] = ‘data’>

Explain architecture of Angular ?

Building Blocks of AngularCMT-BMS-DDP

Angular is composed with the following “building blocks”:

  1. Component : Application state + Application logic
  2. Metadata : Details about the component / module etc.
  3. Template : Design logic (HTML)
  4. Data Binding : Connection between HTML element and Component property
  5. Module : Group of components, directives and pipes.
  6. Service : Re-usable code / business logic.
  7. Dependency Injection : Injecting (loading) Service objects into Components.
  8. Directive : Manipulating DOM elements
  9. Pipe : Transforming values before displaying

Types of compilation in Angular

• Angular framework supports two types of compilation.
Just-In-Time Compilation

  • Templates (.html files) and angular compiler files will be loaded into the browser and then the templates will be compiled automatically at the time of execution, when the component is invoked.
  • The template will be compiled only for the first time, when it invoked, after loading the application files into the browser.
  • Disadvantage: Performance is slower, because every time when you run the application, the templates will be loaded into browser and compiled in the browser; it takes some time to compile.
  • Advantage: The developer need not compile it manually at command prompt, for each modification of code.
  • This is recommended during the development.
  • Bootstrapping (loading app module into the browser) is done by “@angular/platform-browserdynamic” package.
    Ahead-Of-Time Compilation
  • The developer gives “ngc” command in the Command Prompt; Then the “ngc” compiler compiles the templates into javascript code; the compiled javascript code will be loaded into the browser and it directly executes. There is no need of loading “templates (.html files)” and “angular compiler scripts” into the browser.
  • Advantage: Performance is faster, because the templates are already compiled.
  • Disadvantage: The developer need to compile it manually at command prompt, for each
    modification of code.
  • This is recommended in the production server only.
  • Bootstrapping is done by “@angular/platform-browser” package.

How to implement routing in Angular ?

Routing in Angular Application helps us to navigate across the application from one view to another view. It also allows us to maintain the state, implement modules, and then loads the modules based on the roles of the user.

Adding Routing in Angular:

When you are creating an angular 9 application, at the time of creation it is asking whether you want to add angular routing to your project or not. If you select yes, then it automatically add the routing model in your project. If you select no then you need to add it manually. You can use the below CLI code to generate the router in Angular Application.

ng generate module app-routing –flat –module=app

Here –flat puts the file in src/app folder instead of its own folder and –module=app tells the CLI to register it in the imports array of the AppModule.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { StudentComponent } from './student/student.component';
import { StudentdetailComponent } from './studentdetail/studentdetail.component';

const routes: Routes = [
    path:'studentLink', component:StudentComponent
    path:'studentdetailsLink', component: StudentdetailComponent

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }

Note: While generating the link you need to use the string studentLink and studentdetailsLink. Let us see how to use these routing path to generate link and navigates.

Generating to Links:

In order to generate links, open app.component.html file and then copy and paste the following code in it.

Router Link: Client side
Router Link: Server side

Sometimes it is also required to set the route dynamically based on some condition and that can be done at server side. For your application to work with server side rendering, the element hosting directive has to be a link (anchor) element.

It is also possible to navigate to a route from code.
To do so, we need angular router and this need to be done in your typescript file. The syntax is given below.

Router Link: Server side

Once we have the router, then the navigation is quite simple. Just call the navigate function or Router. This function takes an array. The first element of the array defines the route we want to navigate. The second is optional and allows us to pass a route parameter. The syntax is given below.

Understanding Angular Routing with an example
Let us see an example to understand this:

First modify the app.component.ts file as shown below.

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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
    constructor(private router : Router){}

<h2>Angular Routing Example</h2>

<button (click)="GetStudent()">Student</button>
<button (click)="GetStudentDetails()">GetStudentDetails</button>

Redirecting Routes in Angular:

When the application start, it navigates to the empty route by default. We can configure the router to redirect to a named route by default. So, a redirect route translates the initial relative URL (”) to the desired default path. For example, if may want to redirect to Login page or registration page by default when the application start. Then you need to configure the redirectTo as shown below.

Redirecting Routes in Angular Application

A redirect route requires a pathMatch property to tell the router how to match a URL to the path of a route. The router throws an error if you don’t.
For the special case of an empty URL we also need to add the pathMatch: ‘full’ property so angular knows it should be matching exactly the empty string and not partially the empty string.

Lazy Loaded Module Example in Angular 10/9 with loadChildren & Dynamic Import

Lazy loading is the process of loading some features of your Angular application only when you navigate to their routes for the first time. This can be useful for increasing your app performance and decreasing the initial size of the bundle transmitted to the user’s browser.

You now need to use the dynamic import syntax to import your module in the loadChildren property of Angular Router routes.

The dynamic import API is a standard browser’s API introduced in modern browers. It’s promise-based and gives you access to the module, from where the module’s class can be called.

Adding an Angular 10 Module

We can only lazy-load modules in Angular so let’s generate a feature module using the Angular CLI 10:

$ ng generate module admin

Next, we can also add a couple of components in our module:

$ ng generate component admin/login
$ ng generate component admin/dashboard

Using loadChildren to Lazy-Load your Angular 10 Module

Angular provides the loadChildren property of a route’s path to specify the module that needs to be lazy loaded when it’s first navigated to.

Open the src/app/app-routing.module.ts file and update it as follows:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
{ path: 'admin', loadChildren: () => import(`./admin/admin.module`).then(m => m.AdminModule) },

  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }

In loadChildren, we use the dynamic import syntax to lazy-load (load-at-demand) the admin module.

Note: The routing module file should be automatically created by the CLI if you opted for automtically adding routing in your project, otherwise you need to create it manually and add the required code for setting up the router.

Configuring Routes in your Angular 10 Feature Module

After configuring the route to lazy-load your feature module, you’ll next need to add routing to the various components of the admin module which needs to have its own routes seprated from the main routing module that resides in the src/app/app-routing.module.ts file.

Go ahead and create a admin/admin-routing.module.ts file and add the following code:

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

import { LoginComponent } from './login/login.component';
import { DashboardComponent } from './dashboard/dashboard.component';

const routes: Routes = [
    { path: '', component: LoginComponent },
    { path: 'dashboard', component: dashboardComponent }

  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
export class AdminRoutingModule { }

We create the routes to the various components of our admin module and we include these routes in the admin routing module.

We need to feed the routes to the Angular Router using the forChild() method instead of the forRoot() module.

Note: We could also automatically generate the routing module for the admin module using the --routing switch i.e ng generate module admin --routing --module=app.

Open the src/app/admin/admin.module.ts file and import the exported admin routing module as follows:

import { AdminRoutingModule } from './admin-routing.module';

Next, add it to the imports array of the admin module:

  imports: [
  declarations: [LoginComponent, DashboardComponent]
export class AdminModule { }

Define Services ?

A service can contain a value or function or combination of both. The Services in angular are injected into the application using the dependency injection mechanism.

Why do we need a service in Angular?

Whenever you need to reuse the same data and logic across multiple components of your application, then you need to go for angular service. That means whenever you see the same logic or data-access code duplicated across multiple components, then you need to think about refactoring the same logic or data access code into a service.

There is a principle in software development i.e. DRY (Don’t Repeat Yourself) and using services in angular safely follow this principle. The logic or data is implemented in a services and the service can be used across multiple components of your angular application. So, services is a mechanism used to share the functionality between the components.

Differentiate between ng serve and ng build?

ng serveng build
The ng serve command is intentionally for fast, local and iterative developments and also for builds, watches and serves the application from a local CLI development server.The ng build command is intentionally for building the apps and deploying the build artifacts.
The command does not generate an output folder.The output folder is – dist/.
The ng serve builds artifacts from memory instead for a faster development experience.The ng build command generates output files just once and doesn’t serve them.

Injectable link

Decorator that marks a class as available to be provided and injected as a dependency.

providedIn?Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:
root‘ : The application-level injector in most apps.
platform‘ : A special singleton platform injector shared by all applications on the page.
any‘ : Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.

The providedIn property tells the Angular dependency injection with the “scope” of our service in the application i.e where it can be provided.

ng build

Compiles an Angular app into an output directory named dist/ at the given output path. Must be executed from within a workspace directory.

ng build <project> [options]
ng b <project> [options]

The command can be used to build a project of type “application” or “library”. When used to build a library, a different builder is invoked, and only the ts-configconfiguration, and watch options are applied. All other options apply only to building applications.

The application builder uses the webpack build tool, with default configuration options specified in the workspace configuration file (angular.json) or with a named alternative configuration. A “production” configuration is created by default when you use the CLI to create the project, and you can use that configuration by specifying the --configuration="production" or the --prod option.

The configuration options generally correspond to the command options. You can override individual configuration defaults by specifying the corresponding options on the command line. The command can accept option names given in either dash-case or camelCase. Note that in the configuration file, you must specify names in camelCase.

Some additional options can only be set through the configuration file, either by direct editing or with the ng config command. These include assetsstyles, and scripts objects that provide runtime-global resources to include in the project. Resources in CSS, such as images and fonts, are automatically written and fingerprinted at the root of the output folder.

For further details, see Workspace Configuration.

Explain ViewChild and ViewChildren?

DOM manipulation is responsible for modifying existing DOM elements and changing their current appearance or behavior. You may also need to modify other crucial parts of an application, such as components, directives, and other DOM elements. Both ViewChild and ViewChildren are used to communicate between the components to access the data.

@ViewChild and @ViewChildren are the types of decorators used to access the child component class and its different properties into the parent component. It’s similar to the inheritance.

The @ViewChild decorator is used to query a single DOM element from the DOM tree and lets you manipulate it. To select an element from the template, three different parameters can be used.

  • Selector: The selector of the element to query. It can be a directive type or a name.
  • Read: Read a different token from the queried elements.
  • Static: This is one of the new features introduced in Angular 8, and it indicates whether to resolve query results before change detection runs.

Unlike @ViewChild, the @ViewChildren decorator is used to accessing multiple elements. The response of the element list will always be a QueryList.

The QueryList will always be updated whenever any child element added, updated, or removed from the HTML DOM tree.

Why do we need Template reference variables / Local Reference variable?

Let me explain this with an example.Let’s say we have some basic DOM elements in our template view. It can be anything like

<h2>I am h2</h2>
<p>I am Paragraph</p>

And we want to access the content of h2 tag element inside our template but not in the component class. After accessing it, we also want to display below the parent div. How can we do that?

 The answer is “Template Reference variable”. Yes, by placing a template or local reference variable over that element.

Angular provides us, a way of capturing a reference to any specific dom element, component or directive in order to use it somewhere in our template itself.

<h2 #h2Elm>I am h2</h2>
<p>I am Paragraph</p>

we can do the same here for component and directives too

<hello name="Template Ref Variable" #helloRef></hello>
{{}} //   Template Ref Variable

Note: The identifier name used for the template reference variable should be unique and should not conflict with any other template reference variable.Well! I told you that you cannot access that template reference variable inside the component class or typescript logic but still, you can use that variable by passing it through a method which will be called by the event listener.

<label for="Name">Name</label>
<input type="text" #nameInput>
<button (click)="onSaveName(nameInput)">Save Name</button>

Passing that local variable with omitting # symbol.

import {
} from '@angular/core';
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  constructor() {}
  onSaveName(name: HTMLInputElement) {
    console.log(( < HTMLInputElement > name).value);

Angular Forms Guide – Template Driven and Reactive Forms

What are @Input() and @Output() ?

@Input() and @Output() give a child component a way to communicate with its parent component. @Input() allows a parent component to update data in the child component. Conversely, @Output() allows the child to send data to a parent component.

Property binding diagram


@Output() marks a property in a child component as a doorway through which data can travel from the child to the parent.

The child component uses the @Output() property to raise an event to notify the parent of the change. To raise an event, an @Output() must have the type of EventEmitter, which is a class in @angular/core that you use to emit custom events.

What is Content Projection? Content projection with ng-content

How Angular components communicate?

Four Ways for Communication Between Components

  1. Binding (@Input & @Output)
  2. Reference (@ViewChild & @ContentChild)
  3. Provider (Service)
  4. Template Outlet

Is it a good practice to pass data using services?

Angular provides 3 different ways of parent-child interaction.

The suggested way for those interactions is via bindings (Input/Output). However, if the data does not belong to the parent component, a service is probably the better way. It is more clear and keeps the data hierarchy concise.

For components that are not close in the hierarchy, a service is probably the only way.

What Is ViewEncapsulation in Angular?