#1 What is Angular Framework?
Angular is a popular open-source front-end web application framework maintained by Google and a community of developers. It is used for building dynamic single-page web applications (SPAs). Key features include:
- Two-way data binding
- Directives
- Dependency injection
- Templating
- MVC (Model-View-Controller) architecture
- Routing
- Services
#2 What is Angular CLI and what are its benefits?
Angular CLI (Command Line Interface) is a powerful tool to initialize, develop, scaffold, and maintain Angular applications. Its benefits include:
- Automated project setup and boilerplate generation
- Built-in development server with live reloading
- Simplified build process for production deployment
- Easy code scaffolding for components, services, modules, etc.
- Integration with testing frameworks like Jasmine and Karma
#3 What is Angular Module?
An Angular module is a mechanism to group components, directives, pipes, and services that are related to a specific feature of an application. Modules help in organizing between different parts of an application.
#4 What is data binding in Angular?
Data binding is the automatic synchronization of data between the model and the view components in Angular. It allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding (divided into 3 categories) which differ in the way the data is flowing:
1 From the Component to the DOM:
- Interpolation:
{{ value }}
Adds the value of a property from the component.
<li> Name: {{customer.name}} </li>
<li> Age: {{customer.age}} </li>
- Property Binding:
[property]="value"
The Value is passed from the component to the specified property or simple HTML attribute.
<input type=email [value]="user.email">
2 From the DOM to the Component:
- Event Binding:
(event)="function()
When a specific DOM event happens (e.g., click, change, keydown), call the specified method in the component.
<button (click)="submitData()"></button>
3 Two-way Binding:
- Two-way data binding:
[(ngModel)] = “value”
Two way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync.
<input type=email [(ngModel)]="user.email">
#5 What is the difference between constructor and ngOnInit?
1 Constructor:
- The
constructor
method is a Typescript feature used to initialize class members or perform any setup required when an instance of a class is created. It's a standard feature of any TypeScript class. - In Angular, the constructor is primarily used for dependency injection. Angular's dependency injection system injects the required dependencies into the component or service's constructor.
- The constructor is executed before Angular initializes the component's view and binds data to it. It's mainly used for initializing properties and injecting services, but it's not recommended to perform heavy logic or access DOM elements in the constructor.
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
constructor() {
// Initialization logic here
}
}
2 ngOnInit:
- ngOnInit is a lifecycle hook provided by Angular. It's called once, after the first ngOnChanges hook when Angular initializes the component.
- ngOnInit is typically used for initialization tasks that rely on input bindings or component's own properties being initialized.
- This hook is commonly used to retrieve data from a server, perform initialization logic, or set up subscriptions.
- It's important to note that ngOnInit is executed after the constructor, so any initialization logic that depends on the component being fully initialized should be placed here.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
constructor() {
// Constructor logic here
}
ngOnInit(): void {
// Initialization logic that depends on component being fully initialized
}
}
#6 What is a service?
A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components.
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable({ // The Injectable decorator is required for dependency injection to work
// providedIn option registers the service with a specific NgModule
providedIn: 'root', // This declares the service with the root app (AppModule)
})
export class RepoService{
constructor(private http: Http){
}
fetchAll(){
return this.http.get('https://api.github.com/repositories');
}
}
// The above service uses Http service as a dependency
#7 What is dependency injection in Angular?
Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.
#8 What are lifecycle hooks?
Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The representation of lifecycle in pictorial representation as follows,
The description of each lifecycle method is as below,
- ngOnChanges: When the value of a data bound property changes, then this method is called.
- ngOnInit: This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
- ngDoCheck: This is for the detection and to act on changes that Angular can't or won't detect on its own.
- ngAfterContentInit: This is called in response after Angular projects external content into the component's view.
- ngAfterContentChecked: This is called in response after Angular checks the content projected into the component.
- ngAfterViewInit: This is called in response after Angular initializes the component's views and child views.
- ngAfterViewChecked: This is called in response after Angular checks the component's views and child views.
- ngOnDestroy: This is the cleanup phase just before Angular destroys the directive/component.
#9 What is the purpose of async pipe?
The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes.
Let's take a time observable which continuously updates the view for every 2 seconds with the current time.
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time: Observable<string>;
constructor() {
this.time = new Observable((observer) => {
setInterval(() => {
observer.next(new Date().toString());
}, 2000);
});
}
}
#10 What is a bootstrapping module?
Every application has at least one Angular module, the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule
. The default structure of AppModule
generated by AngularCLI would be as follows:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
/* the AppModule class with the @NgModule decorator */
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
#11 What is HttpClient and its benefits?
Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest
interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient
which is based on top of XMLHttpRequest
interface. This client is available from @angular/common/http
package. You can import in your root module as below:
import { HttpClientModule } from '@angular/common/http';
The major advantages of HttpClient can be listed as below,
- Contains testability features
- Provides typed request and response objects
- Intercept request and response
- Supports Observable APIs
- Supports streamlined error handling
#12 Explain on how to use HttpClient
with an example?
In Angular, HttpClient
is a built-in Angular service that allows you to make HTTP requests to a server. It simplifies the process of communicating with a server by providing methods to perform various types of HTTP operations such as GET, POST, PUT, DELETE, etc.
Here's a step-by-step guide on how to use HttpClient
with an example:
1 Import HttpClientModule
- First, you need to import
HttpClientModule
in your Angular module (app.module.ts
or any other module where you need to intend to useHttpClient
).
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule // import HttpClientModule after BrowserModule.
],
declarations: [ /* Components, Directives, Pipes */ ],
bootstrap: [ /* AppComponent */ ]
})
export class AppModule { }
2 Inject the HttpClient
into the application:
- Next, inject
HttpClient
into your Angular Service or component where you want to make HTTP requests.
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
// Your HTTP request methods will go here
}
3 Making HTTP Requests
- Now, you can use the methods provided by
HttpClient
(get
,post
,put
,delete
, etc.) to make HTTP requests. Here's an example of making a GET request:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
// Example GET request
getData(): Observable<any> {
return this.http.get<any>('https://api.example.com/data');
}
}
4 Handling Responses:
- You can subscribe to the
Observable
returned byHttpClient
methods to handle the response.
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
responseData: any;
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.dataService.getData().subscribe(
(data) => {
this.responseData = data;
},
(error) => {
console.error('Error fetching data:', error);
}
);
}
}
5 Displaying Data in the Template
- Finally, you can use the retrieved data in your component's template.
<div *ngIf="responseData">
<h2>Data:</h2>
<pre>{{ responseData | json }}</pre>
</div>
#13 What is RxJS?
RxJS, short for Reactive Extensions for JavaScript, is a library for reactive programming using Observables, which make it easier to compose asynchronous or callback-based code. It's a library for handling asynchronous data streams, often used in Angular for dealing with HTTP requests, event handling, and managing state.
Here are some key aspects of RxJS:
Observables:
Observables are a fundamental part of RxJS. They are similar to Promises but with a difference: they can handle multiple values over time. Observables represent a stream of data that can be observed over time. These streams can emit values asynchronously and can be manipulated, transformed, and combined in various ways.
Operators:
RxJS provides a rich set of operators that allow you to manipulate and transform data streams. Operators are functions that take an observable as input and return a new observable with modified behavior. Some common operators include map, filter, mergeMap, switchMap, concat, zip, and many more.
Schedulers:
Schedulers control the execution of observables. They determine when and where the code associated with an observable will be executed. RxJS provides various built-in schedulers like async, queue, asap, animationFrame, etc., which allow you to control the concurrency and execution context of observables.
Subjects:
Subjects are a special type of observable that can act as both a source of observable values and an observer that can subscribe to other observables. They are often used for multicasting and for representing event streams or state in an application.
Subscription Management:
RxJS provides methods for managing subscriptions to observables. Subscriptions are used to listen to the values emitted by an observable. They can be unsubscribed to release resources and prevent memory leaks.
#14 What is subscribing?
Subscribing in the context of RxJS refers to the act of attaching an observer (also known as a subscriber) to an observable. Observables emit values or events over time, and subscribers listen to these emissions and react accordingly.
When you subscribe to an observable, you effectively start listening to the data stream emitted by that observable. This allows you to react to any values emitted by the observable, perform side effects, or manipulate the data in some way.
Here's a basic example of subscribing to an observable in RxJS:
import { Observable } from 'rxjs';
// Create an observable that emits values over time
const observable = new Observable<number>(observer => {
observer.next(1);
observer.next(2);
observer.next(3);
observer.complete();
});
// Subscribe to the observable
const subscription = observable.subscribe({
next: value => console.log('Received value:', value),
error: err => console.error('Error:', err),
complete: () => console.log('Observable complete')
});
// Unsubscribe from the observable when no longer needed
subscription.unsubscribe();
#15 What is an observable?
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.
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Hello from a Observable!');
}, 2000);
});
#16 What is an observer?
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);
#17 What is the difference between promise and observable?
Feature | Promise | Observable |
---|---|---|
Single vs. Multiple Values | Represents a single value that may be available now, or in the future, or never. | Represents a stream of values that may be emitted over time. |
Execution | Eager execution | Lazy execution |
Cancellation | Does not support cancellation | Supports cancellation through unsubscribe() method |
Error Handling | .catch() method or second argument to .then() | error callback in subscribe() method or error handling operators |
Composition and Transformation | Limited composition capabilities | Rich set of operators for easy composition, transformation, and manipulation |
Time | Time-agnostic | Can represent asynchronous data streams over time |
#18 What are directives in Angular and its types?
In Angular, directives are markers on a DOM element that tell Angular to do something to that element or its children. They are a way to extend HTML with new behavior or functionality
There are three types of directives in Angular:
1 Component Directives:
- In Angular, components are the basic building blocks, which control a part of the UI for any application.
- A component is defined using the @Component decorator. Every component consists of three parts, the template which loads the view for the component, a stylesheet which defines the look and feel for the component, and a class that contains the business logic for the component.
- Components are the most common type of directive in Angular. They are directives with templates and can have their own view and data bindings. Components encapsulate the behavior and appearance of a custom element. In Angular, every application has at least one component, known as the root component.
- These directives have a view, a stylesheet and a selector property.
- For creating a component, inside the command terminal, navigate to the directory of the application created, and run the following command:
ng generate component header
Orng g c header
. - One can see the generated component inside
src/app/header
folder.
Example:
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
// Component logic here
}
2 Attribute Directives:
- Attribute directives change the appearance or behavior of an element by modifying its attributes. They are used as regular HTML attributes on elements.
Example:
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
<div [appHighlight]="color">Highlighted Text</div>
3 Structural Directives:
- Structural directives alter the structure of the DOM by adding or removing elements based on conditions. They are used as regular HTML attributes preceded by an asterisk (*).
Example:
export class AppComponent {
isLoggedIn = true;
username = 'John Doe';
}
<div *ngIf="isLoggedIn">Welcome, {{ username }}</div>
<div *ngFor="let x of details" >
<p>{{x.name}}</p>
<p> {{x.address}}</p>
<p>{{x.age}}</p>
</div>
*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.
#19 What are Modules?
In Angular, modules are a way to organize an application into cohesive blocks of functionality. Modules help in managing the complexity of large applications by providing a mechanism for grouping related components, directives, pipes, and services together. They promote modularity, reusability, and maintainability in Angular applications.
A module is a place where we can group components, directives, services, and pipes. Module decides whether the components, directives, etc can be used by other modules, by exporting or hiding these elements. Every module is defined with a @NgModule
decorator.
By default, modules are of two types:
- Root Module
- Feature Module
Every application can have only one root module whereas, it can have one or more feature modules.
A root module imports BrowserModule, whereas a feature module imports CommonModule.
Here's an example of the module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header.component';
import { FooterComponent } from './footer.component';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Here are some key points about modules in Angular:
- NgModule Decorator:
- Modules in Angular are defined using the
@NgModule
decorator. This decorator takes a metadata object that specifies various properties of the module, such as declarations, imports, providers, and exports.
- Modules in Angular are defined using the
- Declaration:
- The declarations property of
@NgModule
is an array of components, directives, and pipes that belong to the module. Components declared in the module can be used within templates of other components in the same module.
- The declarations property of
- Imports:
- The imports property of
@NgModule
is an array of other modules that are imported into the current module. Imported modules can provide additional functionality, such as common directives, pipes, or services, to the current module.
- The imports property of
- Providers:
- The providers property of
@NgModule
is an array of services that are available to all components and directives within the module. Services provided at the module level are singleton instances, meaning there is only one instance of the service for the entire application.
- The providers property of
- Exports:
- The exports property of
@NgModule
is an array of components, directives, and pipes that are made available to other modules that import this module. Exported components, directives, and pipes can be used in the templates of components in other modules.
- The exports property of
- Bootstrap Component:
- In Angular applications, there is usually a root module that bootstraps the application by specifying the main component to be rendered. The bootstrap property of
@NgModule
is used to specify the root component of the application.
- In Angular applications, there is usually a root module that bootstraps the application by specifying the main component to be rendered. The bootstrap property of
In this example:
- The AppModule is the root module of the application.
- It declares three components: AppComponent, HeaderComponent, and FooterComponent.
- It imports the BrowserModule, which provides essential services and directives for running Angular applications in the browser.
- It specifies AppComponent as the bootstrap component, which will be the starting point of the application.
To create a feature module, run the following command: ng g m test-module
By running this command, the module will be created at src/app/test-module/test-module.module.ts
Below are the contents of it:
test-module.module.ts
:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class TestModuleModule { }
As one can see, CommonModule
is imported since this is a feature module.
#20 What is transpiling in Angular?
Transpiling is the process of transforming the source code of one programming language into the source code of another. Typically, in Angular, this implies translating TypeScript to JavaScript. ypeScript (or another language like as Dart) can be used to develop code for your Angular application, which is subsequently transpiled to JavaScript. This occurs naturally and internally