Prepare Interview

Exams Attended

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Angular Interview Questions and Answers

Experienced / Expert level questions & answers

Ques 1. What happens if you use script tag inside template?

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

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

export class InnerHtmlBindingComponent {

  // For example, a user/attacker-controlled value from a URL.

  htmlSnippet = 'Template <script>alert("0wned")</script> <b>Syntax</b>';

}

Is it helpful? Add Comment View Comments
 

Ques 2. What are template expressions in Angular?

A template expression produces a value similar to any Javascript expression. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive. In the property binding, a template expression appears in quotes to the right of the = symbol as in [property]="expression". In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}},

<h3>{{username}}, welcome to Angular</h3>

The below javascript expressions are prohibited in template expression

  1. assignments (=, +=, -=, ...)
  2. new
  3. chaining expressions with ; or ,
  4. increment and decrement operators (++ and --)

Is it helpful? Add Comment View Comments
 

Ques 3. What are template statements?

A template statement responds to an event raised by a binding target such as an element, component, or directive. The template statements appear in quotes to the right of the = symbol like (event)="statement".

Let's take an example of button click event's statement

<button (click)="editProfile()">Edit Profile</button>

In the above expression, editProfile is a template statement. The below JavaScript syntax expressions are not allowed.

  1. new
  2. increment and decrement operators, ++ and --
  3. operator assignment, such as += and -=
  4. the bitwise operators | and &
  5. the template expression operators

Is it helpful? Add Comment View Comments
 

Ques 4. How do you categorize data binding types in Angular?

Binding types can be grouped into three categories distinguished by the direction of data flow. They are listed as below,

  1. From the source-to-view
  2. From view-to-source
  3. View-to-source-to-view

The possible binding syntax can be tabularized as below,

Data directionSyntaxType
From the source-to-view(One-way)1. {{expression}} 2. [target]="expression" 3. bind-target="expression"Interpolation, Property, Attribute, Class, Style
From view-to-source(One-way)1. (target)="statement" 2. on-target="statement"Event
View-to-source-to-view(Two-way)1. [(target)]="expression" 2. bindon-target="expression"Two-way

Is it helpful? Add Comment View Comments
 

Ques 5. What is a custom pipe in Angular?

Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,

  1. A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library For example,

    @Pipe({name: 'myCustomPipe'})

  2. The pipe class implements the PipeTransform interface's transform method that accepts an input value followed by optional parameters and returns the transformed value. The structure of pipeTransform would be as below,

    interface PipeTransform {

      transform(value: any, ...args: any[]): any

    }

  3. The @Pipe decorator allows you to define the pipe name that you'll use within template expressions. It must be a valid JavaScript identifier.

    template: `{{someInputValue | myCustomPipe: someOtherValue}}`

Is it helpful? Add Comment View Comments
 

Ques 6. Give an example of custom pipe in Angular?

You can create custom reusable pipes for the transformation of existing value. For example, let us create a custom pipe for finding file size based on an extension,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'customFileSizePipe'})

export class FileSizePipe implements PipeTransform {

  transform(size: number, extension: string = 'MB'): string {

  return (size / (1024 * 1024)).toFixed(2) + extension;

  }

}

Now you can use the above pipe in template expression as below,

template: `

  <h2>Find the size of a file</h2>

  <p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>

  `

Is it helpful? Add Comment View Comments
 

Ques 7. What is the difference between pure and impure pipe in Angular?

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.

Is it helpful? Add Comment View Comments
 

Ques 8. What is RxJS in Angular?

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';

Is it helpful? Add Comment View Comments
 

Ques 9. What is subscribing in Angular?

An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.

Creates an observable sequence of 5 integers, starting from 1

const source = range(1, 5);

// Create observer object
const myObserver = {
  next: x => console.log('Observer got a next value: ' + x),
  error: err => console.error('Observer got an error: ' + err),
  complete: () => console.log('Observer got a complete notification'),
};

// Execute with the observer object and Prints out each item
source.subscribe(myObserver);
// => Observer got a next value: 1
// => Observer got a next value: 2
// => Observer got a next value: 3
// => Observer got a next value: 4
// => Observer got a next value: 5
// => Observer got a complete notification

Is it helpful? Add Comment View Comments
 

Ques 10. What is an observable in Angular?

An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS. The observables are created using new keyword.

Let see the simple example of observable,

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello from a Observable!');
  }, 2000);
});

Is it helpful? Add Comment View Comments
 

Ques 11. What is an observer in Angular?

Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure,

interface Observer<T> {
  closed?: boolean;
  next: (value: T) => void;
  error: (err: any) => void;
  complete: () => void;
}

A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below,

myObservable.subscribe(myObserver);


Note: If you don't supply a handler for a notification type, the observer ignores notifications of that type.

Is it helpful? Add Comment View Comments
 

Ques 12. What is the difference between promise and observable?

ObservablePromise
Declarative: Computation does not start until subscription so that they can be run whenever you need the resultExecute immediately on creation
Provide multiple values over timeProvide only one
Subscribe method is used for error handling which makes centralized and predictable error handlingPush errors to the child promises
Provides chaining and subscription to handle complex applicationsUses only .then() clause

Is it helpful? Add Comment View Comments
 

Ques 13. What is multicasting in Angular?

Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution.

Let's demonstrate the multi-casting feature,

var source = Rx.Observable.from([1, 2, 3]);
var subject = new Rx.Subject();
var multicasted = source.multicast(subject);

// These are, under the hood, `subject.subscribe({...})`:
multicasted.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
multicasted.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

// This is, under the hood, `s

Is it helpful? Add Comment View Comments
 

Ques 14. How do you perform error handling in observables in Angular?

You can handle errors by specifying an error callback on the observer instead of relying on try/catch which are ineffective in asynchronous environment.

For example, you can define error callback as below,

myObservable.subscribe({
  next(num) { console.log('Next num: ' + num)},
  error(err) { console.log('Received an errror: ' + err)}
});

Is it helpful? Add Comment View Comments
 

Ques 15. What are the utility functions provided by RxJS?

The RxJS library also provides below utility functions for creating and working with observables.

  1. Converting existing code for async operations into observables
  2. Iterating through the values in a stream
  3. Mapping values to different types
  4. Filtering streams
  5. Composing multiple streams

Is it helpful? Add Comment View Comments
 

Ques 16. What are observable creation functions in Angular?

RxJS provides creation functions for the process of creating observables from things such as promises, events, timers and Ajax requests. Let us explain each of them with an example:


Create an observable from a promise:

import { from } from 'rxjs'; // from function
const data = from(fetch('/api/endpoint')); //Created from Promise
data.subscribe({
 next(response) { console.log(response); },
 error(err) { console.error('Error: ' + err); },
 complete() { console.log('Completed'); }
});


Create an observable that creates an AJAX request:

import { ajax } from 'rxjs/ajax'; // ajax function
const apiData = ajax('/api/data'); // Created from AJAX request
// Subscribe to create the request
apiData.subscribe(res => console.log(res.status, res.response));


Create an observable from a counter:

import { interval } from 'rxjs'; // interval function
const secondsCounter = interval(1000); // Created from Counter value
secondsCounter.subscribe(n =>
  console.log(`Counter value: ${n}`));

Create an observable from an event:

import { fromEvent } from 'rxjs';
const el = document.getElementById('custom-element');
const mouseMoves = fromEvent(el, 'mousemove');
const subscription = mouseMoves.subscribe((e: MouseEvent) => {
  console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
  });

Is it helpful? Add Comment View Comments
 

Ques 17. What will happen if you do not supply handler for observer?

Normally an observer object can define any combination of next, error and complete notification type handlers. If you don't supply a handler for a notification type, the observer just ignores notifications of that type.

Is it helpful? Add Comment View Comments
 

Ques 18. What are angular elements?

Angular elements are Angular components packaged as custom elements(a web standard for defining new HTML elements in a framework-agnostic way). Angular Elements hosts an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs, thus, providing a way to use Angular components in non-Angular environments.

Is it helpful? Add Comment View Comments
 

Ques 19. What are custom elements in Angular?

Custom elements (or Web Components) are a Web Platform feature which extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code. The browser maintains a CustomElementRegistry of defined custom elements, which maps an instantiable JavaScript class to an HTML tag. Currently this feature is supported by Chrome, Firefox, Opera, and Safari, and available in other browsers through polyfills.

Is it helpful? Add Comment View Comments
 

Ques 20. Do I need to bootstrap custom elements in Angular?

No, custom elements bootstrap (or start) automatically when they are added to the DOM, and are automatically destroyed when removed from the DOM. Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular.

Is it helpful? Add Comment View Comments
 

Ques 21. What are the mapping rules between Angular component and custom element?

The Component properties and logic maps directly into HTML attributes and the browser's event system. Let us describe them in two steps,

  1. The createCustomElement() API parses the component input properties with corresponding attributes for the custom element. For example, component @Input('myInputProp') converted as custom element attribute my-input-prop.
  2. The Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name. For example, component @Output() valueChanged = new EventEmitter() converted as custom element with dispatch event as "valueChanged".

Is it helpful? Add Comment View Comments
 

Most helpful rated by users:

Related differences

Jquery vs AngularJSAngularJS vs NodeJSAngularJS vs Angular
Angular vs React

Related interview subjects

PHP interview questions and answers - Total 27 questions
jQuery interview questions and answers - Total 22 questions
React interview questions and answers - Total 40 questions
Dojo interview questions and answers - Total 23 questions
Ajax interview questions and answers - Total 58 questions
ASP interview questions and answers - Total 82 questions
Angular interview questions and answers - Total 50 questions
Oracle JET(OJET) interview questions and answers - Total 54 questions
ExtJS interview questions and answers - Total 50 questions
Angular JS interview questions and answers - Total 21 questions
JavaScript interview questions and answers - Total 59 questions
©2023 WithoutBook