Angular Practical Flashcards

These advanced questions cover real-world scenarios and libraries you may encounter when building or scaling Angular applications. They will help you demonstrate practical knowledge and experience during interviews.

1
Q

What libraries do you use for state management in Angular, and how do they work?

A

In Angular, popular libraries for state management include:

NgRx:
It implements the Redux pattern, using actions, reducers, selectors, and effects to manage the application state in a predictable way. It centralizes state, allowing components to easily access and update it.

Akita:
A less complex state management library that focuses on maintaining a simple store structure with entities and active entities for better performance and easier API management.

NgXs:
A state management library that is simpler than NgRx, using decorators and plain TypeScript classes for actions and state. It integrates well with Angular’s DI and is less boilerplate-heavy.

// Example of using NgRx:
this.store.dispatch(new AddItem({ id: 1, name: ‘Item’ }));
this.store.select(‘items’).subscribe(items => console.log(items));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you handle API requests and error management in large Angular applications?

A

In larger applications, managing API requests and errors requires a robust approach:

  • Interceptor: Use HttpInterceptor to centralize error handling and log requests/responses globally.
  • Service-based architecture: Use Angular services for making API requests and managing business logic.
  • Retry mechanism: Use RxJS operators like retry and catchError to handle failed requests.
  • Global error handling: Implement a global error handler using ErrorHandler to log and display errors in a consistent manner.

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error) => {
console.error('Error occurred:', error);
return throwError(error);
})
);
}
}</any></any>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Which Angular UI component libraries can be used in projects?

A

There are several UI libraries that can be used in Angular projects:

Angular Material: A comprehensive set of pre-built components following Material Design guidelines, providing responsive UI components like buttons, cards, dialog boxes, and tables.

PrimeNG: Another powerful UI library offering a wide range of customizable components, such as data tables, charts, form elements, and more.

NG Bootstrap: A UI library that brings the full power of Bootstrap into Angular using native Angular directives.

Ant Design for Angular: A UI library based on Ant Design, offering components with a clean, minimalist design.

<mat-table [dataSource]=”data”>

<ng-container>
<th mat-header-cell *matHeaderCellDef> Position </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>

</mat-table>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you optimise performance in large-scale Angular applications?

A

To optimise performance in large Angular applications:

  • Lazy loading: Implement lazy loading for feature modules, loading them only when necessary.
  • OnPush change detection strategy: Use the OnPush change detection strategy to reduce the number of change detection cycles.
  • AOT (Ahead-of-Time) compilation: Use AOT to compile the application during the build process for faster rendering and smaller bundle sizes.
  • TrackBy with ngFor: Use trackBy with ngFor to improve performance by only updating changed items in a list.
  • Bundle optimisation: Use Angular’s ng build –prod with optimisations such as tree-shaking, dead code elimination, and minification.

// Using OnPush Change Detection Strategy:
@Component({
selector: ‘app-example’,
changeDetection: ChangeDetectionStrategy.OnPush,
template: <p>{{ data }}</p>,
})
export class ExampleComponent { }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you implement internationalisation (i18n) in Angular?

A

Internationalisation (i18n) in Angular can be achieved using Angular’s built-in i18n tools or third-party libraries like ngx-translate.

  • Built-in i18n: Angular’s official support for localisation uses message extraction (ng extract-i18n), translation files, and a runtime loader for managing different languages.
  • ngx-translate: This third-party library provides more flexibility by loading translations dynamically and supporting features like fallback languages and parameterised strings.

// Using ngx-translate
this.translateService.use(‘en’);

<p>{{ 'HELLO' | translate }}</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How would you implement form validation in a real-world Angular application?

A

Form validation can be handled in two ways:

Template-driven forms:
Validation is done using Angular directives like required, minlength, and pattern.

Reactive forms:
Validation logic is handled programmatically using FormControl and FormGroup, allowing for more flexibility, including custom validators and cross-field validation.

// Example of reactive form validation
this.form = this.fb.group({
email: [’’, [Validators.required, Validators.email]],
password: [’’, Validators.required],
});

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you implement real-time updates in Angular using WebSockets or RxJS?

A

For real-time data, Angular applications can use WebSockets or server-sent events (SSE) with RxJS to manage live updates.

WebSockets: Use the native WebSocket API or libraries like ngx-socket-io to handle real-time communication between client and server.

RxJS: Combine WebSockets with RxJS to handle streams of real-time data efficiently.

const socket = new WebSocket(‘ws://example.com/socket’);
const messages = fromEvent(socket, ‘message’).pipe(map(event => event.data));
messages.subscribe(data => console.log(data));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are some key best practices for writing maintainable Angular code in large projects?

A

To ensure maintainable code in large Angular applications:

  • Modular architecture: Break down the app into feature modules and lazy-load them where appropriate.
  • Component reusability: Write components that are reusable and not tightly coupled to specific features.
  • DRY (Don’t Repeat Yourself): Extract shared logic into services, utilities, and base components.
  • Strong typing with TypeScript: Use interfaces and strong typing to make the code safer and more predictable.
  • Linting and formatting: Use tools like TSLint or ESLint to enforce coding standards and maintain consistency.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you implement file upload functionality in an Angular application?

A

File uploads in Angular can be implemented using the HttpClient with FormData to send multipart file data to the backend. You can create a custom component for selecting and uploading files, handling the file validation, and progress tracking.

uploadFile(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append(‘file’, file);

this.http.post(‘api/upload’, formData).subscribe(response => {
console.log(‘File uploaded successfully’);
});
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you manage authentication and authorisation in Angular applications?

A

Authentication in Angular is commonly handled using:

JWT (JSON Web Tokens): The user logs in, and the server returns a JWT, which is stored in localStorage or sessionStorage and sent with HTTP requests via an interceptor.

OAuth: For third-party authentication, OAuth services like Google and Facebook can be integrated.

Route guards: Use CanActivate and CanLoad route guards to restrict access to certain routes based on the user’s authentication status or roles.

canActivate(): boolean {
return this.authService.isLoggedIn();
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are services in Angular, and how do you create them?

A

Services in Angular are used to share logic, manage data, or perform specific tasks across components. Services are typically classes with specific functionality, like HTTP requests, shared data management, or utility functions. You create a service using the Angular CLI:

ng generate service my-service

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you inject services into components?

A

To inject the service into a component, use Angular’s Dependency Injection (DI). You inject the service in the constructor of the component where you need it.

@Injectable({
providedIn: ‘root’, // Makes it a singleton service
})
export class MyService {
getData() {
return ‘Service Data’;
}
}

@Component({
selector: ‘app-example’,
template: <p>{{ data }}</p>,
})
export class ExampleComponent {
data: string;

constructor(private myService: MyService) {
this.data = this.myService.getData();
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are observables in Angular?

A

Observables are a key part of Angular’s reactive programming model, allowing you to handle asynchronous operations such as HTTP requests, events, or streams of data.
They are provided by RxJS and can emit multiple values over time. You can subscribe to observables to react to emitted values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you use observables for asynchronous operations?

A

For example, when retrieving data from an API, you typically work with observables from Angular’s HttpClient:

import { HttpClient } from ‘@angular/common/http’;
import { Observable } from ‘rxjs’;

export class MyService {
constructor(private http: HttpClient) {}

fetchData(): Observable<any> {
return this.http.get('https://api.example.com/data');
}
}</any>

@Component({
selector: ‘app-example’,
template: <p *ngIf="data">{{ data }}</p>,
})
export class ExampleComponent {
data: any;

constructor(private myService: MyService) {
this.myService.fetchData().subscribe(
(response) => (this.data = response),
(error) => console.error(error)
);
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you handle data retrieval in Angular, especially in large applications?

A

In large applications, handling data retrieval efficiently requires a well-structured approach:

  • Service-based architecture: Create services that handle all HTTP requests and expose methods to fetch data.
  • Caching: Use observables with caching mechanisms to avoid redundant API calls.
  • Resolvers: Implement Angular resolvers to prefetch data before a route is activated, ensuring the component receives the necessary data when initialised.
  • RxJS operators: Use operators like map, switchMap, catchError, and retry to process and manage data streams.

this.http.get(‘api/items’).pipe(
map((data) => this.transformData(data)),
retry(3),
catchError((error) => {
console.error(‘Error fetching data’, error);
return throwError(error);
})
);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you store and manage data in an Angular application?

A

There are several ways to store and manage data in Angular:

  • Local storage or session storage: For storing small amounts of data on the client-side, such as user preferences or JWT tokens.
  • State management libraries (NgRx, Akita, NGXS): For managing complex or global state in large applications.
  • Services: Use Angular services to store shared data between components, or handle data persistence by communicating with a backend API.
  • IndexedDB or WebSQL: For storing larger datasets on the client-side, such as caching offline data.

// Example using localStorage
localStorage.setItem(‘token’, ‘123456’);
const token = localStorage.getItem(‘token’);

17
Q

How do you manage data loading in Angular using lazy loading?

A

Lazy loading allows you to load feature modules only when they are needed, reducing the initial bundle size and improving load times. To set up lazy loading:

  1. Create a feature module:
    “ng generate module feature –route feature –module app.module”
  2. Configure routing: Add a lazy-loaded route to the feature module.
    const routes: Routes = [
    {
    path: ‘feature’,
    loadChildren: () =>
    import(‘./feature/feature.module’).then((m) => m.FeatureModule),
    },
    ];
  3. Lazy load components: The feature module will only be loaded when the user navigates to the corresponding route, reducing the initial bundle size.
18
Q

How do you implement a service that retrieves and stores data from a backend API?

A

To implement a service for data retrieval and storage, you use HttpClient to communicate with the backend API. This service can handle CRUD operations (Create, Read, Update, Delete) and be injected into components for use.

@Injectable({
providedIn: ‘root’,
})
export class DataService {
private apiUrl = ‘https://api.example.com/data’;

constructor(private http: HttpClient) {}

// Retrieve data
getData(): Observable<any> {
return this.http.get(this.apiUrl);
}</any>

// Store data
postData(data: any): Observable<any> {
return this.http.post(this.apiUrl, data);
}
}</any>

19
Q

How do you handle errors when retrieving or storing data in Angular?

A

Error handling in Angular is done using HttpInterceptor for global error management or by using catchError in individual API calls.

  • Interceptor: Centralize error handling for all HTTP requests.
  • Retry mechanism: Use RxJS operators like retry to handle transient failures and retry requests.
  • Error logging: Log errors to a monitoring service or server for later analysis.

this.http.get(‘api/items’).pipe(
catchError((error) => {
console.error(‘Error occurred:’, error);
return throwError(error); // Optionally show a user-friendly message
})
);

20
Q

How do you implement pagination when retrieving data from an API in Angular?

A

Pagination can be implemented by making paginated API requests and displaying data in a component. The backend API should support pagination by providing page numbers, sizes, and total counts.

getPaginatedData(page: number, size: number): Observable<any> {
const params = new HttpParams()
.set('page', page.toString())
.set('size', size.toString());</any>

return this.http.get(‘api/data’, { params });
}

You can then bind the results to a table or list in the template and manage pagination using Angular Material’s paginator component or a custom solution.

21
Q

What are RxJs in Angular?

A

RxJs is a library that provides reactive programming support for Angular applications. It allows you to work with asynchronous data streams and handle events over time. RxJs is based on Observables, which are data streams that can be subscribed to and processed using operators. It provides a powerful and flexible way to handle complex asynchronous operations in Angular.

22
Q

What exactly is a parameterised pipe?

A

A parameterised pipe in Angular is a pipe that accepts one or more arguments, also known as parameters. Pipes transform data in Angular templates, and parameterised pipes allow you to customise the transformation based on specific requirements. By passing parameters to a pipe, you can modify its behaviour and apply different transformations to the data.

23
Q

What are class decorators?

A

Class decorators in Angular are a type of decorator that can be applied to a class declaration. They are used to modify the behaviour of the class or add additional functionality. Class decorators are defined using the @ symbol followed by the decorator name and are placed immediately before the class declaration. They can be used for various purposes, such as adding metadata, applying mixins, or extending the functionality of a class.

24
Q

What are Method decorators?

A

Method decorators in Angular are decorators that can be applied to methods within a class. They are used to modify the behaviour of the method or add additional functionality. Method decorators are defined using the @ symbol followed by the decorator name and are placed immediately before the method declaration. They can be used for tasks like logging, caching, or modifying the method’s behaviour based on specific conditions.

24
Q

What are property decorators?

A

Property decorators in Angular are decorators that can be applied to class properties. They are used to modify the behaviour of the property or add additional functionality. Property decorators are defined using the @ symbol followed by the decorator name and are placed immediately before the property declaration. They can be used for tasks like validation, memoization, or accessing metadata associated with the property.

25
Q

What are router links?

A

Router links in Angular are used for navigation within an application. They are defined using the routerLink directive and provide a way to navigate to different routes or components. Router links can be used in HTML templates and are typically placed on anchor (<a>) tags or other clickable elements. By specifying the destination route or component, router links allow users to navigate between different parts of an Angular application.</a>

26
Q

What exactly is the router state?

A

The router state in Angular represents the current state of the Angular router. It contains information about the current route, including the URL, route parameters, query parameters, and other related data. The router state can be accessed and manipulated using the Angular Router service. It provides a way to programmatically navigate, retrieve information about the current route, and handle route changes in Angular applications.

27
Q

What does Angular Material mean?

A

Angular Material is a UI component library for Angular applications. It provides a set of pre-built and customisable UI components, such as buttons, forms, navigation menus, and dialog boxes, that follow the Material Design guidelines. Angular Material simplifies the process of building consistent and visually appealing user interfaces in Angular. It offers a range of features and styles that can be easily integrated into Angular projects.

28
Q

What is transpiling in Angular?

A

Transpiling in Angular refers to the process of converting TypeScript code into JavaScript code that web browsers can execute. Angular applications are built using TypeScript, a superset of JavaScript that adds static typing and additional features to the language. Since browsers can only run JavaScript, the TypeScript code needs to be transpiled into JavaScript before it can be executed. This is typically done using the TypeScript compiler (tsc) or build tools like Angular CLI.

29
Q

What are HTTP interceptors?

A

HTTP interceptors in Angular are a feature that allows you to intercept HTTP requests and responses globally. Interceptors provide a way to modify or handle HTTP requests and responses at a centralised location before they reach the server or client. This can be useful for logging requests, adding authentication headers, handling errors, or modifying request/response data. Interceptors can be registered in the Angular module and are executed in a specific order based on the request/response pipeline.

30
Q

What is Change Detection, and how does the Change Detection Mechanism work?

A

Change Detection in Angular is a mechanism that determines when and how to update the user interface based on changes in the application’s data model. Angular uses a tree of change detectors to track changes in component properties and update the DOM accordingly. When a change occurs, Angular performs a change detection process, which involves checking each component’s properties for changes and updating the DOM if necessary. The change detection mechanism keeps the UI in sync with the application’s data.

31
Q

What is a bootstrapping module?

A

A bootstrapping module in Angular is the main entry point of an Angular application. It is responsible for starting the application and initialising the root component. The bootstrapping module is typically defined in the main.ts file and is configured in the Angular AppModule. It sets up the necessary environment, loads required modules, and invokes the Angular platform to start the application. The bootstrapping module plays a crucial role in the Angular application’s lifecycle.

32
Q

How do you choose anc from a component template?

A

You can use various techniques to choose an element from a component template in Angular. One common approach is to use template reference variables. The template defines these variables using the # symbol followed by a name. You can then reference the element using the variable name in your component code. Another approach is to use Angular directives like ViewChild or ViewChildren to query for elements based on CSS selectors or component types. These directives provide more flexibility and control when selecting elements from the component template.

33
Q

How do you deal with errors in observables?

A

When dealing with errors in observables in Angular, catchError operator can be used to handle and recover from errors. This operator allows you to provide a fallback value or execute alternative logic when an error occurs. You can chain the catchError operator after the observable that might produce an error and define a callback function to handle the error. Within the callback function, you can perform error handling tasks such as logging the error, displaying an error message to the user, or initiating a retry mechanism.

34
Q

How to include SASS into an Angular project?

A

To include SASS (Syntactically Awesome Style Sheets) into an Angular project, you need to install the required dependencies and configure the project accordingly. Follow these steps:

  • Install the node-sass package by running the command npm install node-sass –save-dev.
  • Update the angular.json file in your project’s root directory.
  • Locate the styles property under architect > build > options.
  • Change the file extension from .css to .scss to indicate that you are using SASS.
  • Rename your existing CSS files to SCSS files (e.g., styles.css to styles.scss).
  • Restart the Angular development server for the changes to take effect.

Once SASS is included in your Angular project, you can write your styles using SASS syntax, which provides additional features like variables, mixins, and nested selectors.

35
Q

What happens when we use the script tag within a template?

A

Using the script tag within an Angular template is not a recommended practice. Angular templates are intended for defining the structure and layout of the user interface, and including scripts directly within the template goes against the separation of concerns principle. When a script tag is used within a template, the browser treats it as part of the HTML content and attempts to execute it. However, Angular’s template compiler does not process or execute scripts within templates. Instead, scripts should be placed in separate JavaScript files and included using the appropriate Angular mechanisms, such as component logic or Angular modules.

36
Q

Write a code to share data from the Parent to Child Component?

A

To share data from a parent component to a child component in Angular, you can make use of input properties. Input properties allow you to pass data from parent to child components. Here’s an example:

Parent Component:

import { Component } from ‘@angular/core’;
@Component({
selector: ‘app-parent’,
template: <app-child [message]="parentMessage"></app-child>,
})
export class ParentComponent { parentMessage = ‘Hello from parent’;}

Child Component:

import { Component, Input } from ‘@angular/core’;
@Component({
selector: ‘app-child’,
template: <p>{{ message }}</p>,
})
export class ChildComponent {
@Input() message: string;
}

In this example, the parent component (ParentComponent) defines a property parentMessage that holds the data to be shared with the child component (ChildComponent). The parent component then passes this data to the child component using the input property [message]. The child component receives the data through the @Input() decorator and can use it within its template or logic.

37
Q

Create a TypeScript class with a constructor and a function.

A

Here’s an example of a TypeScript class with a constructor and a function:

class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(Hello, my name is ${this.name} and I'm ${this.age} years old.);
}
}
// Usage
const person = new Person(‘John’, 30);
person.sayHello();

In this example, the Person class represents a person with a name and an age property. The constructor is used to initialise these properties when creating an instance of the class. The sayHello function is a method of the class that logs a greeting message using the person’s name and age. Finally, an instance of the Person class is created, and the sayHello function is called to output the greeting message.

38
Q

What is the full form of ng in Angular?

A

In Angular, “ng” stands for “Angular”. It is a convention used in Angular to prefix directives, components, and other Angular-specific entities. For example, ngFor is a built-in Angular directive used for rendering lists based on an array, and ngModel is a directive used for two-way data binding between an input element and a component property. The “ng” prefix helps to distinguish Angular-specific entities from regular HTML elements and attributes.