Angular Cheatsheet 2024
Stacksjar
Posted on August 8, 2024
In this article we are going to see a well curated list of angular interview questions 2021 and answers for experienced as well as freshers
Why were client-side frameworks like Angular introduced?
The advent of modern JavaScript frameworks has made it much easier to build highly dynamic, interactive applications.
JS frameworks are JavaScript code libraries that have pre-written code to use for routine programming features and tasks. It is literally a framework to build websites or web applications around.
A framework is a library that offers opinions about how software gets built. These opinions allow for predictability and homogeneity in an application; predictability allows software to scale to an enormous size and still be maintainable; predictability and maintainability are essential for the health and longevity of software
Angular is an open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. It is a complete rewrite from the same team that built AngularJS. Angular was officially released on the 14th of September 2016.
Angular is a component-based framework which uses declarative HTML templates. At build time, transparently to developers, the framework's compiler translates the templates to optimized JavaScript instructions.
What are lifecycle hooks in Angular?
Angular Lifecycle hooks are different states of an angular applications component or directive through out the time of its instantiation to time when its destroyed. These lifecycle hooks are invoked at different phases and conditions of angular application.
The lifecycle continues with change detection, as Angular checks to see when data-bound properties change, and updates both the view and the component instance as needed.
We can use any of these lifecycle hooks to tap into particular event or state of the application to perform task's as required.
Below are the lifecycle hooks:
ngOnChanges(): Called whenever one or more data-bound input properties change just before before ngOnInit().
ngOnInit(): Called once, after the first ngOnChanges() and angular has insantiated the component
ngDoCheck(): Called on every change detection run, and once after ngOnChanges() and ngOnInit() respectively. The purpose of this lifecycle hook is to act upon changes that Angular can't or won't detect on its own.
ngAfterContentInit(): Called once after the first ngDoCheck(). The purpose of this lifecycle hook is to respond after angular has finished loading any external data into its component.
ngAfterContentChecked(): Called after ngAfterContentInit() and every subsequent ngDoCheck(). The purpose of this lifecycle hook is to check the content projected into the directive or component.
ngAfterViewInit(): Called once after the first ngAfterContentChecked(), This lifecycle hook is invoked when angular initializes the component's views and child views
ngAfterViewChecked(): Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked(). This lifecycle hook is invoked after angular checks the component's views and child views, or the view that contains the directive.
ngOnDestroy(): Called immediately before Angular destroys the directive or component. We can use this lifecycle hook for Cleanup just before Angular destroys the directive or component. Unsubscribe Observables and detach event handlers to avoid memory leaks.
Explain Components, Modules and Services in Angular
Components in Angular are the main building block for Angular applications. Each component consists of 4 files by default .html, .less, .ts and .spec.ts. A component is basically a wrapper for our presentation layer and the logical layer.
An HTML template that declares what renders on the page. A Typescript class that defines behavior. A CSS selector that defines how the component is used in a template.
Module in Angular are basically a container for all the code blocks in the application. We declare and import all services, pipes, directives and components in the default main module created by angular at time of project creation which is the AppModule. We can create more than one modules for our application and lazy or eager load as per our requirement. An angular module is defined with the @NgModule() decorator.
Services in Angular are way of communicating between the components of an Angular application and sharing data between them. We can make our code modular and re-usable by means of services as it can be used across the application. Services in angular are declared with use of the @Injectable() decorator.
What are directives in Angular?
Directives are classes that add additional behavior to elements in your Angular applications. Directives are basically custom HTML attributes which Angular provides us Built in to use and some of which we can create by ourselves.
Below are the different types of Directives
Structural Directives:
These are the type of directives which helps us to create DOM Objects. We can add DOM objects and remove DOM objects inside our application dynamically by using these two directives.
*ngFor: Loop over the Array of objects creating HTML elements on which the directive is used.
*ngIf: Add or remove the HTML element from DOM depending upon the condition specified.
Attribute Directives:
These are the type of directives which helps us to change the look and feel and behavior of our HTML elements, attributes, properties, and components.
NgClass: adds and removes a set of CSS classes.
NgStyle: adds and removes a set of HTML styles.
NgModel: adds two-way data binding to an HTML form element.
Component Directives:
These are the types of directives with a template. This type of directive is the most common directive type. This Specifies that an Angular component is also a type of Directive.
What is Angular Router?
Angular Router is a Routing service for our angular application provided by Angular. Which we can import and use in our Application. We need specify the Array of Routes to this service and import it in our AppModule. This service is required for Navigating through different components/view of our angular application.
What is Angular Material?
Angular Material is a material UI component library built by the Angular team to integrate seamlessly with Angular applications. Angular Material provides built in ready to use components that helps in creating minimal, elegant and functional, HTML elements and pages. It consists of well tested components to ensure performance and reliability with straightforward APIs and consistent cross platform behavior.
Angular Material provides tools that help developers build their own custom components with common interaction patterns. It helps in creating faster, beautiful, and responsive websites. It is inspired by the Google Material Design.
What is string interpolation in Angular?
String Interpolation in Angular is method to bind data from the logical layer to the presentation layer. We can bind our ts variables in our html directly by using this mechanism called as string Interpolation which is denoted by double curly braces.
Below is the example
//ts file
title: String = 'Angular Application';
//html file
{{ title }}
How does one share data between components in Angular?
Following are the most common ways in which we can share data between angular components:
@Input: The @Input method is used when we want to pass data from parent to child.
@Output: The @Ouput method is used when we want to pass data from child to parent by using it EventEmmitter feature.
Services: Services are the most common way of sharing data across multiple components as its declared in the root of the component.
List out differences between AngularJS and Angular
Angular JS is the first ever version of Angular and is based on Javascript. Where as the Angular is completely based on Typescript which is a superset of Javascript and has backward compatibility.
Angular JS, based on JavaScript, uses terms of scope and controllers while Angular uses a hierarchy of components. Angular is component-based while AngularJS uses directives.
Angular is based on modern web applications platform and we can develop cross platform applications with single angular code.
What is AOT compilation?
An Angular application consists mainly of components and their HTML templates. Because the components and templates provided by Angular cannot be understood by the browser directly, Angular applications require a compilation process before they can run in a browser.
For this Angular provides two types of compilers JIT and AOT. JIT stands for Just in Time, and AOT stands for Ahead of Time.
The Angular ahead-of-time (AOT) compiler converts our Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the browser.
We can use either JIT or AOT compiler for building our application.
//To use JIT compiler for Build run
ng build
//To use AOT compiler for Build run
ng build --prod
What are the advantages of AOT?
Smaller application size (Angular compiler excluded)
Faster component rendering (already compiled templates)
Template parse errors detected earlier (at build time)
More secure (no need to evaluate templates dynamically)
How are Angular expressions different from JavaScript expressions?
Like JavaScript expressions, Angular expressions can contain literals, operators, and variables. Unlike JavaScript expressions.
Angular expressions can be written inside HTML. Angular expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.
Angular expressions support filters, while JavaScript expressions do not.
How are observables different from promises?
Observables:
Emit multiple values over a period of time.
Are lazy: they’re not executed until we subscribe to them using the subscribe() method.
Have subscriptions that are cancellable using the unsubscribe() method, which stops the listener from receiving further values.
Provide the map for forEach, filter, reduce, retry, and retryWhen operators.
Deliver errors to the subscribers.
Promises:
Emit a single value at a time.
Are not lazy: execute immediately after creation.
Are not cancellable.
Don’t provide any operations.
Push errors to the child promises.
Explain the concept of Dependency Injection?
In software engineering, Dependency Injection is a technique in which an object receives other objects that it depends on. These other objects are called dependencies. The "injection" refers to the passing of a dependency (a service) into the object (a class) that would use it.
There are basically three types of dependency injection:
Constructor Injection: the dependencies are provided through a class constructor.
Setter Injection: the client exposes a setter method that the injector uses to inject the dependency.
Interface Injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.
Describe the MVVM architecture.
Model–View–ViewModel (MVVM) is a software architectural pattern that facilitates the separation of the development of the presentation layer (the view) – be it via a markup language or GUI code – from the development of the logical layer or back-end logic (the model) so that the view is not dependent on any specific model platform.
Discuss the advantages and disadvantages of using Angular?
Below are the advantages and disadvantages of Angular.
Advantages of Angular:
MVC Architecture implementation
Enhanced Design Architecture
Dependency Injection (DI)
TypeScript: better tooling, cleaner code, and higher scalability
Large community and ecosystem
Powerful Router
Disadvantages of Angular:
Limited SEO options
Steeper learning curve
What is ngOnInit? How to define it?
A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the component/directive is instantiated.
The ngOnInit() method is defined in a component class as below:
class MyComponent implements OnInit {
ngOnInit() {
// some code
}
}
What is ViewEncapsulation in Angular?
View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa
The default ViewEncapsulation is Emulated, this view encapsulation emulates the behavior of shadow DOM by preprocessing (and renaming) the CSS code to effectively scope the CSS to the component's view. Angular adds the CSS to the global styles.
Angular provides there types of View Encapsulation. They are as follows:
Emulated: Styles from main HTML propagate to the component. Styles defined in this component's @Component decorator are scoped to this component only.
Native: Styles from main HTML do not propagate to the component. Styles defined in this
None: Styles from the component propagate back to the main HTML and therefore are visible to all components on the page. Be careful with apps that have None and Native components in the application. All components with None encapsulation will have their styles duplicated in all components with Native encapsulation.
Why prioritize TypeScript over JavaScript in Angular?
TypeScript simplifies JavaScript code, making it easier to read and debug. TypeScript provides highly productive development tools for JavaScript IDEs and practices, like static checking. TypeScript makes code easier to read and understand. With TypeScript, we can make a huge improvement over plain JavaScript.
There are many more benefits of TypeScript over Javascript:
Consistency
Productivity
Maintainability
Modularity
Catch Errors Early
What is a Bootstrapping module in Angular?
Bootstrapping in Angular is a function component in the core ng module that is used for starting up the Angular application. By default the Appcomponent is the default component that will be bootstraped.
Below is the Default code for bootstrapping an angular application in app.module.ts
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent],
schemas: []
})
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.
An Impure Pipe is called for every change detection cycle no matter whether the value or parameter(s) changes.
Below is an example of pipe and its decorator for setting pipe type
@Pipe({
name: 'myCustomPipe',
pure: true // true means this is a Pure Pipe and false means its and Impure Pipe (default is true)
})
export class MyCustomPipe {}
What is RxJS?
The full form of RxJS is Reactive Extension for Javascript. It is a javascript library that uses observables to work with reactive programming that deals with asynchronous data calls, callbacks and event-based programs.
RxJS is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code. RxJS can be used with any other Javascript libraries and frameworks.
What is an observable?
Observables are simply a function that are able to give multiple values over time, either synchronously or asynchronously. You can also consider Observables as lazy Push collections of multiple values.
Observables provide support for passing messages between parts of your application. They are used frequently in Angular and are a technique for event handling, asynchronous programming, and handling multiple values.
We can subscribe to an observable and get values synchronously or asynchronously.
Below is an example of how to create and Observable:
var observable = Rx.Observable.create((observer: any) =>{
observer.next("This is an Observable");
})
observable.subscribe((data)=>{
console.log(data); // output - "This is an Observable"
});
What is an observer?
Observers are just objects with three callbacks, one for each type of notification that an Observable may deliver.
An Observer is a consumer of values delivered by an Observable. Observers are simply a set of callbacks, one for each type of notification delivered by the Observable: next , error , and complete.
Below is an example of Observer and values retrieved after being Subscribed to it:
const observer = {
next: x => console.log('This is next value: ' + x),
error: err => console.error('Observer got an error: ' + err),
};
observable.subscribe(observer);
//OR
observable.subscribe(observer => {
observer.next(10);
observer.error("something went wrong");
});
What are Angular Elements?
Angular elements are Angular components packaged as custom elements (also called Web Components), a web standard for defining new HTML elements in a framework-agnostic way.
A custom element 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.
Live Example of Angular Elements :- Angular Elements Working Example
The custom elements standard is currently supported by browsers like Chrome, Opera, and Safari. To be able to use it Firefox and Edge polyfills are available. The Angular Elements functionality is available with the package @angular/elements.
In order to keep track of all available custom elements the browser maintains a registry in which every elements needs to be registered first. In this registry the name of the tag is mapped to the JavaScript class which controls the behavior and the output of that element.
What is Angular Universal or Angular SSR?
Angular Universal is mechanism provided by Angular team by which you can render your single page angular application on server instead of Browser. Typical Angular applications are Single-Page Applications (aka SPA's) where the rendering occurs on the Browser. This process can also be referred to as client-side rendering (CSR).
Angular Universal is a very helpful and SEO friendly approach for modern web applications.
The Angular Universal provides 2 options:
Server Side Rendering : In this method the requested page will be completely rendered on server and send to the browser
Pre-Rendering : In this method you have to provide a list of routes you want to pre-render then by using the pre rendering command and the routes mentioned it will complete the Build with fully rendered HTML pages
To add Angular Universal to your project use below command:
ng add @nguniversal/express-engine
What are Service Workers in Angular?
Service Worker in Angular is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them.
Service Workers helps in improving your application's performance.
To add Service Workers in your Angular application use below command:
ng add @angular/pwa
Checkout this Article: It covers complete Steps to Add Service Worker in Angular Application
What is Lazy Loading in Angular?
Lazy Loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. It improves the speed of the application load time by splitting the application into several bundles. When the user navigates through the app, the bundles are loaded as required.
Instead of loading the entire web page and rendering it to the user in one go as in bulk loading, the concept of lazy loading assists in loading only the required section and delays the remaining, until it is needed by the user.
Below is an example route for a lazy loaded module:
const routes: Routes = [
{path: '', redirectTo: 'home', pathMatch: 'full'},
{path: 'home', component: HomeComponent},
{path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule'}
];
What is a Shared Module in Angular?
Shared modules in Angular helps you write more organized code in less time, helping you be more productive. Shared modules are an ideal spot to declare components in order to make them reusable. You won’t have to re-import the same components in every module—you’ll just import the shared module.
Creating shared modules allows you to organize and streamline your code. You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your app.
Below is an example of a Shared Module:
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { SharedRoutingModule } from "./shared-routing.module";
import { SharedComponent } from "./components/shared/shared.component";
@NgModule({
declarations: [SharedComponent],
imports: [CommonModule, SharedRoutingModule],
exports: [SharedComponent]
})
export class SharedModule {}
What is DOM Sanitizer in Angular?
Dom Sanitizer in Angular helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing values to be safe to use in the different DOM contexts.
Below are the different methods Provided by Angular for Sanitization and make sure any user data is appropriately escaped for this security context.
//default sanitize data
abstract sanitize(context: SecurityContext, value: string | SafeValue): string | null
//sanitize html
abstract bypassSecurityTrustHtml(value: string): SafeHtml
//sanitize css
abstract bypassSecurityTrustStyle(value: string): SafeStyle
//sanitize scripts
abstract bypassSecurityTrustScript(value: string): SafeScript
//sanitize url
abstract bypassSecurityTrustUrl(value: string): SafeUrl
//sanitize resource urls
abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl
Checkout other Articles in this series:
Part 1 of this series :- Angular Interview Questions Part 1
Part 2 of this series :- Angular Interview Questions Part 2
Part 3 of this series :- Angular Interview Questions Part 3
Posted on August 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024