Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Create a TypeScript class with a constructor and a function.

Answer»
class IB {
name: string;
constructor(message: string) {
this.name = message;
}
greet() {
return "Hello, " + this.name + "How are you";
}
}
let msg = new IB("IB");
2.

Write a code where you have to share data from the Parent to Child Component?

Answer»

You have to share the data amongst the components in numerous situations. It may consist of unrelated, parent-child, or child-parent components.

The @Input decorator allows any data to be sent from parent to child.

// parent component
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<app-child [childMessage]="parentMessage"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
parentMessage = "message from parent"
constructor() { }
}
// child component
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `Say {{ childMessage }}`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
 @Input() childMessage: string;
constructor() { }
}
3.

What is Pipe transform Interface in Angular?

Answer»

An interface used by pipes to accomplish a transformation. Angular calls the transform function with the value of a binding as the first argument and any arguments as the second parameter in list form. This interface is used to implement custom pipes.

Example: 

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'tranformpipe'
})
export class TranformpipePipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
   return null;
 }
}
4.

What are impure pipes?

Answer»

Angular calls an impure pipe for each change detection cycle, independent of the change in the input fields. For each of these pipes, several pipe instances are produced. These pipes' inputs can be altered.

By default, all pipelines are pure. However, as demonstrated below, you can specify impure pipes using the pure property.

Example:

@Pipe({
   name: 'impurePipe',
   pure: false/true   
})
export class ImpurePipe {}
5.

What are pure Pipes?

Answer»

These are pipelines that only employ pure functions. As a result, a pure pipe does not employ any internal state, and the output remains constant as long as the parameters provided remain constant. Angular calls the pipe only when the parameters being provided change. A single instance of the pure pipe is utilized in all components.


6.

What are annotations in Angular ?

Answer»

These are language features that are hard-coded. Annotations are merely metadata that is set on a class to reflect the metadata library. When a user annotates a class, the compiler adds an annotations property to the class, saves an annotation array in it, and then attempts to instantiate an object with the same name as the annotation, providing the metadata into the constructor. Annotations in AngularJs are not predefined, therefore we can name them ourselves.


7.

What are Decorators and their types in Angular?

Answer»

Decorators are a fundamental concept in TypeScript, and because Angular heavily relies on TypeScript, decorators have become an important element of Angular as well.

Decorators are methods or design patterns that are labeled with a prefixed @ symbol and preceded by a class, method, or property. They enable the modification of a service, directive, or filter before it is utilized. A decorator, in essence, provides configuration metadata that specifies how a component, class, or method should be processed, constructed, and used at runtime. Angular includes a number of decorators which attach various types of metadata to classes, allowing the system to understand what all these classes signify and how they should function.

Types of decorators:



  • Method Decorator: Method decorators, as the name implies, are used to add functionality to the methods defined within our class.


  • Class Decorator: Class Decorators are the highest-level decorators that determine the purpose of the classes. They indicate to Angular that a specific class is a component or module. And the decorator enables us to declare this effect without having to write any code within the class.


  • Parameter Decorator: The arguments of your class constructors are decorated using parameter decorators.


  • Property Decorator: These are the second most popular types of decorators. They enable us to enhance some of the properties in our classes.


8.

What is two way data binding in Angular?

Answer»

Data sharing between a component class and its template is referred to as two-way data binding. If you alter data in one area, it will immediately reflate at the other end. This happens instantly and automatically, ensuring that the HTML template and TypeScript code are always up to date. Property binding and event binding are coupled in two-way data binding.

Example: 

app.component.ts

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

@Component({
selector: "app",
templateUrl: "./app.component.html",
})
export class AppComponent {
data = "This is an example component of two way data binding.";
}

app.component.html

<input [(ngModel)]="data"  type="text">
<br> <br>
<h2> You entered the data:  {{data}}</h2>

app.module.ts

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";

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

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

What is data binding in Angular?

Answer»

Data binding is one of the most significant and effective elements for creating communication between the DOM and the component. It makes designing interactive apps easier by reducing the need to worry about data pushing and pulling between the component and the template.

There are Four types of Data binding in Angular: 


  • Property Binding

  • Event Binding

  • String Interpolation

  • Two way data binding

Property Binding: One method of data binding is called property binding. In property binding, we connect a DOM element's property to a field that is a declared property in our TypeScript component code. In reality, Angular transforms string interpolation into property binding internally.

Event Binding: Using event binding, you may respond to DOM events like button clicks and mouse movements. When a DOM event (such as a click, change, or keyup) occurs, the component's designated method is called.

String Interpolation: In order to export data from TypeScript code to an HTML template( view ), String Interpolation is a one way data binding approach. The data from the component is shown to the view using the template expression enclosed in double curly braces. The value of a component property is added by using string interpolation.


10.

What is the scope?

Answer»

In Angular, a scope is an object that refers to the application model. It is a context in which expressions can be executed. These scopes are grouped hierarchically, comparable to the DOM structure of the application. A scope aids in the propagation of various events and the monitoring of expressions.


11.

Explain Components, Modules and Services in Angular

Answer»

For better understanding, I would like you to create an Angular application by running the following inside the command terminal: ng new angularApp

The above command will create an angular application in the directory.

Next, let's move on to understand Components, Modules, and Services.

  • Components

In Angular, components are the basic building blocks, which control a part of the UI for any application.

A component is defined using the @Component decorator. Every component consists of three parts, the template which loads the view for the component, a stylesheet which defines the look and feel for the component, and a class that contains the business logic for the component.

For creating a component, inside the command terminal, navigate to the directory of the application created, and run the following command: ng generate component testOr ng g c test

One can see the generated component inside src/app/test folder. The component will be defined inside test.component.ts and this is how it looks:

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export lass TestComponent implements OnInit {
constructor() {}
ngOnInit() {
}
}

As we can see in the above image, our component is defined with @Component decorator.

  • Modules

A module is a place where we can group components, directives, services, and pipes. Module decides whether the components, directives, etc can be used by other modules, by exporting or hiding these elements. Every module is defined with a @NgModule decorator.

By default, modules are of two types:


  • Root Module

  • Feature Module

Every application can have only one root module whereas, it can have one or more feature modules.

A root module imports BrowserModule, whereas a feature module imports CommonModule.

In the application that we created before, one can see that the root module is defined inside app.module.ts and this is how it looks:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { TestComponent } from './test/text.component';

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

We can see in the above image that the component we created earlier is already imported in the declarations array.

To create a feature module, run the following command: ng g m test-module

The module is created inside the src/app/test-module/test-module.module.ts file:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class TestModuleModule { }

 As one can see, CommonModule is imported since this is a feature module.

  • Services

Services are objects which get instantiated only once during the lifetime of an application. The main objective of a service is to share data, functions with different components of an Angular application.

A service is defined using a @Injectable decorator. A function defined inside a service can be invoked from any component or directive.

To create a service, run the following command: ng g s test-service

The service will be created inside src/app/test-service.service.ts:

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

@Injectable({
providedIn: 'root'
})
export class TestServiceService {

constructor() { }

}

 Any method/function defined inside the TestServiceService class can be directly used inside any component by just importing the service.


12.

What are templates in Angular?

Answer»

A template is a kind of HTML that instructs Angular about how to display a component. An Angular HTML template, like conventional HTML, produces a view, or user interface, in the browser, but with far more capabilities. Angular API evaluates an HTML template of a component, creates HTML, and renders it.

There are two ways to create a template in an Angular component:


  • Inline Template

  • Linked Template

Inline Template: The component decorator's template config is used to specify an inline HTML template for a component. The Template will be wrapped inside the single or double quotes.

Example: 

@Component({
   selector: "app-greet",
   template: `<div>
       <h1> Hello {{name}} how are you ? </h1>
       <h2> Welcome to interviewbit ! </h2>
   </div>`
})

Linked Template: A component may include an HTML template in a separate HTML file. As illustrated below, the templateUrl option is used to indicate the path of the HTML template file.

Example: 

@Component({
   selector: "app-greet",
   templateUrl: "./component.html"
})
13.

What are Single Page Applications (SPA)?

Answer»

Single page applications are web based applications that only need to be loaded once, with new functionality consisting of only minor changes to the user interface. It does not load new HTML pages to display the content of the new page, but rather generates it dynamically. This is made feasible by JavaScript's ability to alter DOM components on the current page. A Single Page Application method is speedier, resulting in a more consistent user experience.


14.

How are Angular expressions different from JavaScript expressions?

Answer»

The first and perhaps, the biggest difference is that Angular expressions allow us to write JavaScript in HTML which is not the case when it comes to JavaScript expressions.

Next, Angular expressions are evaluated against a local scope object whereas JavaScript expressions are against a global window object. Let's understand that better with an example :

Consider the following component named test:   

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

@Component({
selector: 'app-test',
template: `
<h4>{{message}}</h4>
`,
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
message:string = “Hello world”;
constructor() { }

ngOnInit() {
}
}

As one can see that Angular expression is used to display the message property of a component. Since we are using Angular expressions, in the present template, we cannot access a property outside of its local scope, which in this case is TestComponent.

This proves that Angular expressions are always evaluated based on the scope object rather than the global object.

The next difference is how Angular expressions handle null and undefined.

Consider the following JavaScript example:    

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Test</title>
</head>
<body>
<div id="foo"><div>
</body>
<script>
'use strict';
let bar = {};
document.getElementById('foo').innerHTML = bar.x;
</script>
</html>

If you run the above code, you will see undefined displayed on the screen. Although it’s not ideal to leave any property undefined, the user does not need to see this.

Now consider the following Angular example:    

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

@Component({
selector: 'app-new',
template: `
<h4>{{message}}</h4>
`,
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
message:object = {};
constructor() { }

ngOnInit() {
}

}

If you render the above component, you will not see undefined being displayed on the screen.

Next, in Angular expressions, one cannot use loops, conditionals and exceptions.

The difference which makes Angular expressions quite beneficial is the use of pipes. Angular uses pipes(called filters in AngularJS), which can be used to format data before displaying it. Let’s see one predefined pipe in action:    

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

@Component({
selector: 'app-new',
template: `
<h4>{{message | lowercase}}</h4>
`,
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
message:string = "HELLO WORLD";
constructor() { }

ngOnInit() {
}

}

In the above code, we have used a predefined pipe called lowercase, which transforms all the letters in lowercase. Therefore, if you render the above component, you will see “hello world” being displayed.

In contrast, JavaScript does not have the concept of pipes.


15.

List out differences between AngularJS and Angular?

Answer»


  • Architecture

    • AngularJS uses MVC or Model-View-Controller architecture, where the Model contains the business logic, the Controller processes information and the 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.


Find out more.


16.

What are the advantages of Angular over React?

Answer»

Angular vs React:
AngularReact
Angular supports bidirectional data binding as well as mutable data.React only supports unidirectional and immutable data binding.
The biggest benefit of Angular is that it enables dependency injection.React allows us to either accomplish it ourselves or with the aid of a third-party library.
Angular can be used in both mobile and web development.React can only be used in UI development only.
Angular features a wide wide range of tools, libraries, frameworks, plugins, and so on that make development faster and more fun.In React we can use third-party libraries for any features.
Angular uses Typescript.React uses Javascript.

17.

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

Answer»


  • Features that are provided out of the box - Angular provides a number of built-in features like routing, state management, rxjs library and http servicesstraight 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.


18.

How does an Angular application work?

Answer»

Every Angular app consists of a file named angular.json. This file will contain all the configurations of the app. While building the app, the builder looks at this file to find the entry point of the application. Following is an image of the angular.json file:

"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-starter",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/style.css"
]
}
}

 Inside the build section, the main property of the options object defines the entry point of the application which in this case is main.ts.

The main.ts file creates a browser environment for the application to run, and, along with this, it also calls a function called bootstrapModule, which bootstraps the application. These two steps are performed in the following order inside the main.ts file: 

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; platformBrowserDynamic().bootstrapModule(AppModule)

In the above line of code, AppModule is getting bootstrapped.

The AppModule is declared in the app.module.ts file. This module contains declarations of all the components.

Below is an example of app.module.ts file:    

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

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

 As one can see in the above file, AppComponent is getting bootstrapped.

This component is defined in app.component.ts file. This file interacts with the webpage and serves data to it.

Below is an example of app.component.ts file:

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}

 Each component is declared with three properties:



  • Selector - used for accessing the component


  • Template/TemplateURL - contains HTML of the component


  • StylesURL - contains component-specific stylesheets

After this, Angular calls the index.html file. This file consequently calls the root component that is app-root. The root component is defined in app.component.ts. This is how the index.html file looks:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>

 The HTML template of the root component is displayed inside the <app-root> tags.

This is how every angular application works.


19.

Why were client-side frameworks like Angular introduced?

Answer»

Back in the day, web developers used VanillaJS and jQuery to develop dynamic websites but, as the logic of one's website grew, the code became more and more tedious to maintain. For applications that use complex logic, developers had to put in extra effort to maintain the separation of concerns for the app. Also, jQuery did not provide facilities for data handling across views.

For tackling the above problems, client-side frameworks like Angular came into the picture, which made life easier for the developers by handling the separation of concerns and dividing code into smaller bits of information (In the case of Angular, called Components).

Client-side frameworks allow one to develop advanced web applications like Single-Page-Application. Not that we cannot develop SPAs using VanillaJS, but by doing so, the development process becomes slower.