Angular Interview Question
Angular Interview Question
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).
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:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [],
bootstrap: [AppComponent]
})
export class AppModule { }
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}
<!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>
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.
Angular vs React:
Angular React
Angular supports bidirectional data binding as well as React only supports unidirectional and
mutable data. immutable data binding.
Angular can be used in both mobile and web React can only be used in UI
Angular React
Architecture
o 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.
o Angular replaces controllers with Components. Components are nothing but
directives with a predefined template.
Language
o AngularJS uses JavaScript language, which is a dynamically typed language.
o 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
o AngularJS does not provide mobile support.
o Angular is supported by all popular mobile browsers.
Structure
o While developing larger applications, the process of maintaining code
becomes tedious in the case of AngularJS.
o In the case of Angular, it is easier to maintain code for larger applications as
it provides a better structure.
Expression Syntax
o 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.
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 :
@Component({
selector: 'app-test',
template: `
<h4>{{message}}</h4>
`,
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
message:string = “Hello world”;
constructor() { }
ngOnInit() {
}
}
<!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.
@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.
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:
@Component({
selector: 'app-new',
template: `
<h4>{{message | lowercase}}</h4>
`,
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
message:string = "HELLO WORLD";
constructor() { }
ngOnInit() {
}
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.
Inline Template
Linked Template
Example:
@Component({
selector: "app-greet",
template: `<div>
<h1> Hello {{name}} how are you ? </h1>
<h2> Welcome to interviewbit ! </h2>
</div>`
})
Example:
@Component({
selector: "app-greet",
templateUrl: "./component.html"
})
9. What are directives in Angular?
Every directive has its own behaviour and can be imported into various components
of an application.
Types of directives:
1. Component directives
2. Structural directives
In the above example, we can *ngIf and *ngFor directives being used.
*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 behaviour of a DOM element.
Let’s understand attribute directives by creating one:
In the command terminal, navigate to the directory of the angular app and type the
following command to generate a directive: ng g directive blueBackground
The following directive will be generated. Manipulate the directive to look like this:
@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>
Components
In Angular, components are the basic building blocks, which control a part of the UI
for any application.
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:
Modules
Root Module
Feature Module
Every application can have only one root module whereas, it can have one or more
feature modules.
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:
@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.
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class TestModuleModule { }
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.
@Injectable({
providedIn: 'root'
})
export class TestServiceService {
constructor() { }
}
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.
Property Binding
Event Binding
String Interpolation
Two way data binding
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.
Example:
app.component.ts
@Component({
selector: "app",
templateUrl: "./app.component.html",
})
export class AppComponent {
data = "This is an example component of two way data binding.";
}
app.component.html
app.module.ts
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
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:
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.
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.
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 {}
Example:
19. Write a code where you have to share data from the Parent to
Child Component?
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() { }
}
First time users can instantly see a view of the application. This benefits in
providing better user experience.
Many search engines expect pages in plain HTML, thus, Universal can make sure
that your content is available on every search engine, which leads to better SEO.
Any server-side rendered application loads faster since rendered pages are
available to the browser sooner.
View encapsulation specifies if the component's template and styles can impact the
entire program or vice versa.
Native: The component does not inherit styles from the main HTML. Styles defined
in this component's @Component decorator are only applicable to this component.
Emulated (Default): The component inherits styles from the main HTML. Styles set
in the @Component decorator are only applicable to this component.
None: The component's styles are propagated back to the main HTML and
therefore accessible to all components on the page. Be wary of programs that have
None and Native components. Styles will be repeated in all components with Native
encapsulation if they have No encapsulation.
RxJS is an acronym that stands for Reactive Extensions for JavaScript. It is used to
enable the use of observables in our JavaScript project, allowing us to do reactive
programming. RxJS is utilized in many popular frameworks, including Angular since
it allows us to compose our asynchronous or callback-based code into a sequence
of operations executed on a data stream that releases values from a publisher to a
subscriber. Other programming languages, such as Java and Python, offer packages
that allow them to develop reactive programs utilizing observables.
Most of the time, rxJs is used in HTTP calls with angular. Because http streams are
asynchronous data, we can subscribe to them and apply filters to them.
Example: The following is a simple example of how RxJs can be utilized with HTTP
calls.
Promise Observable
Emits a single
Emits multiple values over a period of time
value
Not Lazy Lazy. An observable is not called until we subscribe to the observable
Cannot be
Can be cancelled by using the unsubscribe() method
cancelled
When you run the above Observable, you can see messages being displayed in the
following order:
As you can see, observables are lazy. Observable runs only when someone
subscribes to them hence, the message “Before subscribing…” is displayed ahead of
the message inside the observable.
Now let’s consider a Promise:
Running the above promise, the messages will be displayed in the following order:
As you can see the message inside Promise is displayed first. This means that a
promise runs before the then method is called. Therefore, promises are eager.
The next difference is that Promises are always asynchronous. Even when the
promise is immediately resolved. Whereas an Observable, can be
both synchronous and asynchronous.
The biggest feature of using observables is the use of operators. We can use
multiple operators on an observable whereas, there is no such feature in a promise.
Let’s break it down, dependencies in angular are nothing but services which have
functionality. The functionality of a service, can be needed by various components
and directives in an application. Angular provides a smooth mechanism by which
we can inject these dependencies into our components and directives.