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>';
}
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
- assignments (=, +=, -=, ...)
- new
- chaining expressions with ; or ,
- increment and decrement operators (++ and --)
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.
- new
- increment and decrement operators, ++ and --
- operator assignment, such as += and -=
- the bitwise operators | and &
- the template expression operators
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,
- From the source-to-view
- From view-to-source
- View-to-source-to-view
The possible binding syntax can be tabularized as below,
Data direction | Syntax | Type |
---|---|---|
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 |
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,
- A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library For example,
@Pipe({name: 'myCustomPipe'})
- 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
}
- 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}}`
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>
`
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.
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';
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
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);
});
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.
Ques 12. What is the difference between promise and observable?
Observable | Promise |
---|---|
Declarative: Computation does not start until subscription so that they can be run whenever you need the result | Execute immediately on creation |
Provide multiple values over time | Provide only one |
Subscribe method is used for error handling which makes centralized and predictable error handling | Push errors to the child promises |
Provides chaining and subscription to handle complex applications | Uses only .then() clause |
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
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)}
});
Ques 15. What are the utility functions provided by RxJS?
The RxJS library also provides below utility functions for creating and working with observables.
- Converting existing code for async operations into observables
- Iterating through the values in a stream
- Mapping values to different types
- Filtering streams
- Composing multiple streams
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}`);
});
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.
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
.
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.
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.
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,
- 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
. - 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".
Most helpful rated by users: