Top Angular Interview Questions and Answers for 2021 - IQCode

Common Angular Interview Questions

Below are some common interview questions related to Angular:


//Code snippets could be added here.

Why Learning Angular is Essential for Modern Web Development

If you've learned the JavaScript programming language, you might be considering learning one or more JavaScript frameworks. The fact is, knowing various in-demand frameworks has become essential in today's technology industry. Not only will immersing yourself in these frameworks expand your knowledge, but it can also increase your chances of securing a job.

One of the most popular JavaScript frameworks to learn is Angular. In this article, we will take a deep dive into the fundamentals and building blocks of Angular by answering commonly asked interview questions.

Reasons for Introducing Client-Side Frameworks Such as Angular

In the past, web developers utilized VanillaJS and jQuery for creating dynamic websites. However, as the complexity of website logic grew, managing the code became increasingly difficult. For applications that required complex logic, developers needed to expend more effort to maintain separation of concerns for the app. Furthermore, jQuery did not provide data handling facilities for views. To address these concerns, client-side frameworks like Angular emerged, simplifying the lives of developers by managing separation of concerns and dividing code into smaller components. Client-side frameworks enable developers to build advanced web applications such as Single-Page-Applications. While it is possible to create SPAs using VanillaJS, doing so slows down the development process.

How Angular Applications Work

Angular applications are made up of several files including `angular.json`, `main.ts`, `app.module.ts`, and `app.component.ts`. To begin, the `angular.json` file contains the configurations for the app and the entry point of the application is defined in the `main` property of the options object in the `build` section of this file.

The `main.ts` file creates a browser environment for the application to run and calls a function called `bootstrapModule()` to bootstrap the application. The `AppModule` is declared and defined in the `app.module.ts` file, which contains all component declarations. Each component is declared with three properties: `selector`, `template/templateUrl`, and `styleUrls`.

The root component `AppComponent` is defined in the `app.component.ts` file, which interacts with the webpage and serves data to it. The `index.html` file calls the root component `AppComponent` and its HTML template is displayed in the `` tags. Simply put, every Angular application follows this architecture to function properly.

Advantages of Angular over Other Frameworks

Angular provides several advantages over other frameworks, such as:

  • Built-in Features: Angular offers a variety of built-in features, such as routing, state management, rxjs library, and HTTP services. This convenience means developers don't have to search and integrate separate libraries.
  • Declarative UI: Angular uses HTML to render an application's user interface. Since HTML is a declarative language, it's much easier to use than JavaScript, enhancing usability and development speed.
  • Long-term Google Support: Google-backed Angular has announced Long-term support for Angular. Therefore, Google plans to continue using the Angular framework and scalability of its ecosystem.

Hence, Angular is an excellent choice for building scalable, maintainable, and feature-rich web applications.

Differences between AngularJS and Angular

When comparing AngularJS and Angular, there are several key differences to be aware of:

Architecture:

AngularJS uses MVC architecture, whereas Angular uses Components that function as directives with predefined templates.

Language:

AngularJS uses JavaScript, while Angular uses TypeScript, which is a statically typed superset of JavaScript. This provides better performance when developing larger applications.

Mobile Support:

AngularJS does not have native mobile support, whereas Angular is supported by popular mobile browsers.

Structure:

Angular provides a better structure for maintaining code in larger applications than AngularJS.

Expression Syntax:

Angular simplifies property and event binding with the use of "[ ]" and "( )" attributes respectively, compared to AngularJS which utilizes ng-directives.


    // AngularJS example of binding an event using ng-click
    <button ng-click="myFunction()"> Click Me </button>

    // Angular example of binding an event using ( ) attribute
    <button (click)="myFunction()"> Click Me </button>


What is AOT Compilation and What Are Its Advantages in Angular?

Angular applications contain components and templates that are not understandable by the browser. Hence, Angular applications need to be compiled before running inside the browser. Angular has two types of compilation: JIT (Just-in-Time) and AOT (Ahead-of-Time).

In JIT compilation, the application compiles inside the browser during runtime, whereas in AOT compilation, the application compiles during the build time.

Using AOT compilation has the following advantages:

  • Since the application compiles before running inside the browser, the browser loads the executable code and renders the application immediately, which leads to faster rendering.
  • In AOT compilation, the compiler sends the external HTML and CSS files along with the application, eliminating separate AJAX requests for those source files, which leads to fewer AJAX requests.
  • Developers can detect and handle errors during the building phase, which helps in minimizing errors.
  • The AOT compiler adds HTML and templates into the JS files before they run inside the browser. Due to this, there are no extra HTML files to be read, which provides better security to the application.

By default, Angular builds and serves the application using a JIT compiler. To use the AOT compiler, the following changes should be made:

ng build --aot
ng serve --aot

Explanation of Components, Modules, and Services in Angular

Components, Modules, and Services in Angular

Angular is a popular JavaScript framework for developing web applications. It is important to understand its basic building blocks, such as Components, Modules, and Services, to use it effectively.

To create an Angular application, run the following command in your terminal:


ng new angularApp

## Components

Components are the basic building blocks of an Angular application. They control a part of the UI, consisting of the view, style, and business logic. Components are defined using the @Component decorator.

To create a component, navigate to the application directory and run either of these commands:


ng generate component test

ng g c test

This will generate the `test` component inside the `src/app/test` folder. The component will look like this:


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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

## Modules

Modules are used to group components, directives, services, and pipes together in an Angular application. Modules determine whether these elements can be used by other modules or not. Modules are defined using the @NgModule decorator.

There are two types of modules: root modules and feature modules. An application can have only one root module, while it can have one or more feature modules. Root modules import BrowserModule, while feature modules import CommonModule.

For instance, in the root module of the `angularApp` application (`app.module.ts`), the `TestComponent` was imported in the `declarations` array as below:


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 { }

To create a feature module named `test-module`, run the following command:


ng g m test-module

The module will be 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 { }

## Services

Services are used to share data and functions among various components of an Angular application. Services have a single instance during the lifetime of the application. Services are defined using the @Injectable decorator and the functions defined inside the service can be invoked from any component or directive.

To create a service named `test-service`, run the following command:


ng g s test-service

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


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

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

  constructor() { }

}

Any method/function defined inside the `TestServiceService` class can be used inside any component by importing the service. This enables easy data sharing and code maintainability.

What are Lifecycle Hooks in Angular? Explain a few Lifecycle Hooks.

Every Angular component goes through a lifecycle consisting of various phases from creation to destruction. Angular provides hooks that allow developers to tap into these phases and trigger changes at specific points in the lifecycle.

The most commonly used Lifecycle Hooks are:

ngOnChanges()

: This hook is called before

ngOnInit()

whenever one or more input properties of the component change. This hook receives a

SimpleChanges

object which contains both the previous and current values of the property.

ngOnInit()

: This hook is called once after

ngOnChanges()

and is used to initialize the component and set its input properties.

ngDoCheck()

: This hook is called after

ngOnChanges()

and

ngOnInit()

and is used to detect and act on changes that cannot be detected by Angular. Developers can implement their own change detection algorithm in this hook.

ngAfterContentInit()

: This hook is called after the first

ngDoCheck()

hook and is used to respond after content is projected inside the component.

ngAfterContentChecked()

: This hook is called after

ngAfterContentInit()

and every subsequent

ngDoCheck()

hook and responds after the projected content is checked.

ngAfterViewInit()

: This hook is called after a component's view or a child component's view is initialized.

ngAfterViewChecked()

: This hook is called after

ngAfterViewInit()

and responds after the component's view or the child component's view is checked.

ngOnDestroy()

: This hook is called just before Angular destroys the component. It is used to clean up the code and detach event handlers.

Developers can use these hooks to implement necessary logic at every phase of a component's lifecycle.

For example, to process a large amount of data during component creation, it's better to perform this operation inside the

ngOnInit()

hook rather than the constructor.

Here's an example of how to use the

ngOnInit()

hook:


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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  constructor() { }

  ngOnInit() {
    this.processData();
  }

  processData(){
    // Do something..
  }

}

Explanation of String Interpolation and Property Binding in Angular

String interpolation and property binding are crucial aspects of data binding in Angular, which allows communication between the component (Model) and its view (HTML template).

Data binding is facilitated through one-way and two-way binding, and in Angular, data from the component can be inserted inside the HTML template. One-way binding enables changes in the component to reflect directly in the HTML template, while bi-directional binding makes it possible to go back and forth.

String interpolation and property binding both support one-way data binding. String interpolation uses double curly braces {{ }} to present data from the component. Angular automatically evaluates the expression inside the curly braces, e.g., {{ 2 + 2 }}, and displays the computed output, i.e., 4, inside the HTML template.

On the other hand, property binding helps to bind the DOM properties of an HTML element to the property of a component. This binding technique is done using the square brackets [ ] syntax.Angular Expressions vs JavaScript Expressions

Introduction

Angular expressions differ from JavaScript expressions in several ways: 1. They allow us to write JavaScript in HTML. 2. They evaluate against a local scope object rather than a global object. 3. They handle null and undefined differently. 4. They do not support loops, conditionals, and exceptions. 5. They have pipes for formatting data before displaying it.

Angular expressions

Angular expressions let us write JavaScript in HTML. Here we are creating a component named "Test". We use Angular expressions to display the "message" property of this component. In this template, we cannot access a property outside of its local scope, that is, "TestComponent".

Null and Undefined handling

In JavaScript, when we leave an undefined property, the users see it on the screen. But in Angular, users will not see undefined being displayed on the screen, i.e., it handles null and undefined differently.

Loops, conditionals, and exceptions

In Angular expressions, we cannot use loops, conditionals, and exceptions. Whereas, JavaScript does not have any such restrictions.

Pipes

Angular expressions allow us to use pipes for formatting data before displaying it. Here, we are creating a component named "NewComponent". We have used a predefined pipe "lowercase" that transforms all letters to lowercase. So, when we render the above component, we can see "hello world" displayed instead of "HELLO WORLD".

Code:


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() {
  }
}

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() {
  }
}

Observable vs Promise: Differences and Examples

Observables and promises are two popular ways of handling asynchronous operations in JavaScript. While both hold similar functionalities, they differ in several ways.

An observable is lazy, whereas a promise is eager. A promise will immediately execute the operation and return the result upon creation while an observable will only execute once a subscriber subscribes to it. Observables can emit multiple values over a period of time, while promises emit a single value.

Example Observable:


const observable = rxjs.Observable.create(observer => {
    console.log('Text inside an observable');
    observer.next('Hello world!');
    observer.complete();
});

console.log('Before subscribing to an Observable');

observable.subscribe((message) => console.log(message));

In the above example, the observable is lazy and will execute only when someone subscribes to it. Hence, console output appears in the following order:


Before subscribing to an Observable 
Text inside an observable 
Hello world!

A promise is always asynchronous, even when it is instantly resolved, unlike observables that can be either synchronous or asynchronous.

Example Promise:


const promise = new Promise((resolve, reject) => {
    console.log('Text inside promise');
    resolve('Hello world!');
});

console.log('Before calling the then method on a Promise');

promise.then(message => console.log(message));

In this example, the promise is eager and executes as soon as it is created. Hence, console output appears in the following order:


Text inside promise 
Before calling the then method on a Promise 
Hello world!

Another difference between promises and observables is that promises can emit only one value, while observables can emit multiple values. Observables can also be canceled using the unsubscribe() method, whereas promises cannot be canceled.

Finally, observables provide operators like map, filter, forEach, reduce, retry, retryWhen, among others, while promises do not support such features.

Server-Side Rendering with Angular Universal

It is true that Angular primarily uses client-side rendering for its applications, but it is also possible to render an Angular application on the server-side using Angular Universal.

By using Angular Universal, there are several benefits that can be gained:

  • Users are able to see a view of the application instantly, improving user experience.
  • Search engines prefer plain HTML pages, which means that Universal can help ensure your content is available and improve SEO.
  • Server-side rendered applications load faster, as rendered pages are available to the browser sooner.

To leverage these benefits, simply implement Angular Universal in your application.

What are Directives in Angular?

In Angular, a directive is a class that is declared with the @Directive decorator. Each directive has its own behavior and can be imported into various components of an application.

When to use a directive? If an application has multiple components that need to have similar functionalities, creating individual functionality for each component can be tedious. In such cases, we can create a directive that has the required functionality and import the directive to components that require the functionality.

Types of Directives:

1. Component Directives: These directives form the main class in Angular and are declared using the @Component decorator instead of @Directive decorator. These directives have a view, a stylesheet and a selector property.

2. Structural Directives: These directives are generally used to manipulate DOM elements. They have a ‘ * ’ sign before them. We can apply these directives to any DOM element. Some built-in structural directives are *ngIf and *ngFor directives.

*ngIf is used to check a boolean value and if it’s truthy, the div element will be displayed.

*ngFor is used to iterate over a list and display each item of the list.

3. Attribute Directives: These directives are used to change the look and behavior of a DOM element.

Creating a Custom Directive: To create a custom attribute directive, navigate to the Angular app's directory and use the following command to generate a directive:

ng g directive blueBackground

Use the following code to manipulate the generated directive:

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

@Directive({
  selector: '[appBlueBackground]'
})
export class BlueBackgroundDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = "blue";
  }
}

`

Now we can apply the above directive to any DOM element:

`
<p appBlueBackground>Hello World!</p>

`How to Share Data Between Components in Angular

To share data between components in Angular, there are several methods to be aware of.

1. Parent to Child using @Input Decorator

In this approach, the parent component passes data to its child component through a property binding. First, let's create the parent component:

    @Component({ selector: 'app-parent', template: ` `, styleUrls: ['./parent.component.css'] }) export class ParentComponent { data = "Message from parent";

constructor() {} }

In this example, we passed the property `data` to the child component.

Now, we can create the child component as follows:

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

@Component({ selector: 'app-child', template: `

{{ data }}

`, styleUrls: ['./child.component.css'] }) export class ChildComponent { @Input() data: string;

constructor() {} }

With the @Input decorator, we can bind the value passed from the parent component to the data variable in the child component.

2. Child to Parent using @ViewChild Decorator

In this approach, the child component passes data to its parent component. Here is an example of the child component:

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

@Component({ selector: 'app-child', template: ` `, styleUrls: ['./child.component.css'] }) export class ChildComponent { data = "Message from child to parent"; @Output() dataEvent = new EventEmitter();

constructor() {}

emitData() { this.dataEvent.emit(this.data); } }

In this example, we are emitting an event in the child component that listens to the button click.

Now, let's create the parent component:

    import { Component } from '@angular/core'; import { ChildComponent } from './../child/child.component';

@Component({ selector: 'app-parent', template: `

{{ dataFromChild }}

`, styleUrls: ['./parent.component.css'] }) export class ParentComponent { dataFromChild: string; @ViewChild(ChildComponent, {static: false}) child: ChildComponent;

ngAfterViewInit() { this.dataFromChild = this.child.data; }

constructor() {} }

In this example, we use ViewChild to get the reference of ChildComponent. Then leveraging AfterViewInit hook, we assign the data property of child component to the dataFromChild property and use it in the parent component's template.

3. Child to Parent using @Output and EventEmitter

This approach involves using @Output and EventEmitter to send data from child to parent. Here is an example of the child component:

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

@Component({ selector: 'app-child', template: ` `, styleUrls: ['./child.component.css'] }) export class ChildComponent { data = "Message from child to parent"; @Output() dataEvent = new EventEmitter();

constructor() {}

emitData() { this.dataEvent.emit(this.data); } }

In this example, we are emitting an event in the child component that listens to the button click.

Then, you can capture the emitted data in the parent component like this:

    

Now, you can handle the emitted data in the `receiveData` function like this:

    receiveData($event){ this.dataFromChild = $event; }

By using these methods, you can easily share data between components in Angular.

Understanding Dependency Injection in Angular

Dependency injection is a design pattern commonly used in Angular applications. It is one of the core concepts of Angular. In simple terms, dependency injection involves injecting services with functionality into components and directives of an application. This makes the services injectable across all components of an application, which ensures a smoother and more efficient development process.

To better understand how dependency injection works, consider the following service:

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

@Injectable({ providedIn: 'root' }) export class TestService { importantValue:number = 42;

constructor() { }

returnImportantValue(){ return this.importantValue; } }

As shown in the code above, the "@Injectable" decorator is added to a class to create injectable dependencies. This service can be injected into any component, like the one shown below:

import { TestService } from './../test.service'; import { Component, OnInit } from '@angular/core';

@Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { value:number;

constructor(private testService:TestService) { }

ngOnInit() { this.value = this.testService.returnImportantValue(); } }

In the component above, the TestService is imported, then instantiated inside the constructor of the component. Finally, the "returnImportantValue" function is used to implement the functionality. This is a simple example of how Angular provides a smooth way to inject dependencies into any component of an application.

Explanation of MVVM Architecture

The MVVM architecture is a design pattern consisting of three parts:

  1. Model
  2. View
  3. ViewModel

The Model holds the data and structure of an entity. It contains data related to an object.

The View is the user interface layer of the application. It displays the data from the Model. In Angular, the View is the HTML template of a component.

The ViewModel is an abstract layer of the application that handles the logic. It manages the data of a Model and displays it in the View. View and ViewModel are connected with two-way data-binding. When there is a change in the View, the ViewModel updates the corresponding data in the Model.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.