Fullstack Interview Questions – Angular

1. Let and var keyword differences

Description:
- `let` and `var` are both used for variable declaration in JavaScript, but they have some differences.
- `let` is block-scoped, while `var` is function-scoped.
- Redeclaring a variable using `let` within the same block is not allowed, whereas it's possible with `var`.
- `let` has a concept called the Temporal Dead Zone (TDZ), which prevents access before declaration, unlike `var`.

Example Code:


let x = 5;
let x = 10; // Error: Identifier 'x' has already been declared

var y = 5;
var y = 10; // No error
    
Let vs. Var

2. Angular component communication @Input, @Output , @ViewChild, services - Databinding oneway and two way

Description:
- Angular components communicate with each other using various mechanisms such as `@Input`, `@Output`, `@ViewChild`, and services.
- `@Input` is used to pass data from a parent component to a child component.
- `@Output` is used to emit events from a child component to a parent component.
- `@ViewChild` allows a parent component to query and access child components or DOM elements.
- Data binding in Angular includes one-way binding (`{{}}`) and two-way binding (`[()]`).

Example Code:


// Parent component template
<app-child [inputData]="parentData" (outputEvent)="handleOutput($event)"></app-child>

// Child component TypeScript
@Input() inputData: any;
@Output() outputEvent = new EventEmitter();

// Child component HTML
<button (click)="outputEvent.emit('Data from child')">Send Data</button>
    
Angular Component Communication

3. Routing in Angular and default route setting

Description:
- Routing in Angular enables navigation between different components.
- You can configure routes in the AppRoutingModule using the RouterModule.
- Default route setting specifies which component should be displayed when the application is loaded.

Example Code:


const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent }
];
    
Routing in Angular

4. What are derivatives and types - Component, Attribute Directive, Structural Directive

Description:
- In Angular, derivatives are types of directives that allow you to extend HTML functionality.
- Components are directives with a template.
- Attribute directives change the appearance or behavior of a DOM element, component, or another directive.
- Structural directives modify the structure of the DOM by adding, removing, or manipulating elements.

Example Code:


<div appHighlight>Highlighted Text</div>
<div *ngIf="condition">Conditional Content</div>
    
Directives in Angular

5. Custom Pipe and uses

Description:

  • Custom pipes in Angular are used to transform data before displaying it in the template.
  • They are defined using the @Pipe decorator and implementing the PipeTransform interface.
  • Custom pipes can be used to filter, format, or manipulate data in various ways.

Example Code:


@Pipe({
  name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
  transform(value: any, ...args: any[]): any {
    // Transform logic here
  }
}
Custom Pipe

6. Services and making it static - providedIn Root

Description:

  • Services in Angular are singleton objects that are instantiated once and shared across the application.
  • By default, services are provided at the root level using the @Injectable decorator with the providedIn property set to 'root'.
  • This makes the service available to the entire application.

Example Code:


@Injectable({
  providedIn: 'root'
})
export class MyService {
  // Service logic here
}
Angular Service

7. Grid or Table which is faster and why? What are the differences

Description:

  • Grid and table layouts serve different purposes and have different performance characteristics.
  • Grid layouts are generally faster for rendering large amounts of data with complex layouts, as they offer more flexibility and better support for responsive design.
  • Tables, on the other hand, are better suited for tabular data with fixed columns and rows.
  • The choice between grid and table depends on the specific requirements of the application.

Example Code:



Item 1
Item 2
Item 3
Column 1 Column 2 Column 3
Data 1 Data 2 Data 3

8. Event binding and Event Listener

Description:

  • Event binding in Angular allows you to listen for and respond to user actions such as clicks, keypresses, and mouse movements.
  • Event listeners are used to attach event handlers to HTML elements and execute a function when the event occurs.

Example Code:






document.getElementById("myButton").addEventListener("click", myFunction);

9. Storage Cache and how to get value and setting

Description:

  • Storage cache in web development refers to storing data temporarily in the browser's storage for quicker access.
  • In JavaScript, you can use localStorage or sessionStorage for storage caching.
  • To get a value from storage cache, you can use localStorage.getItem(key) or sessionStorage.getItem(key).
  • To set a value in storage cache, you can use localStorage.setItem(key, value) or sessionStorage.setItem(key, value).

Example Code:


// Get value from localStorage
const data = localStorage.getItem('key');

// Set value in localStorage
localStorage.setItem('key', 'value');

10. Login Form - ng form

Description:

  • A login form is a common feature in web applications for authenticating users.
  • In Angular, you can create a login form using Angular Forms module, specifically ngForm.
  • ngForm is a directive in Angular that binds an HTML form to a model object.

Example Code:


<form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
    <input type="text" name="username" ngModel required>
    <input type="password" name="password" ngModel required>
    <button type="submit">Login</button>
</form>

11. Rest service implementation in Angular

Description:

  • Implementing RESTful services in Angular involves creating services to interact with RESTful APIs.
  • You can use Angular's built-in HttpClient module to make HTTP requests to the server.
  • REST services typically involve CRUD operations (Create, Read, Update, Delete) on server-side resources.

Example Code:


import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get('https://api.example.com/data');
  }

  // Other CRUD operations
}

12. Promise and Observable differences

Description:

  • Both Promise and Observable are used for handling asynchronous operations in JavaScript and Angular.
  • A Promise represents a single future value, while an Observable represents a stream of values over time.
  • Observables provide powerful operators for composing asynchronous operations, while Promises do not have such built-in capabilities.

Example Code:


// Promise example
const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Data loaded successfully');
  }, 2000);
});

// Observable example
const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Data loaded successfully');
  }, 2000);
});

13. Multicast Delegate and use of Subject

Description:

  • A multicast delegate is a delegate that can have multiple handlers attached to it.
  • In Angular, the Subject class from the RxJS library is often used for implementing multicast behavior.
  • Subjects are both observable and observers, meaning they can emit values and be subscribed to.

Example Code:


import { Subject } from 'rxjs';

const subject = new Subject();

// Subscribe to the subject
subject.subscribe(data => console.log('Observer 1: ', data));

// Emit a value
subject.next('Hello');

// Output: Observer 1: Hello

14. Lazy Loading with examples and route configuration - Module creation

Description:

  • Lazy loading is a technique in Angular where modules are loaded only when they are required.
  • This can significantly improve application performance by reducing initial load times.
  • To implement lazy loading, you need to create separate modules for different parts of your application and configure routes accordingly.

Example Code:


// app-routing.module.ts
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];

// lazy.module.ts
const routes: Routes = [
  { path: '', component: LazyComponent }
];

15. JIT and AOT differences

Description:

  • JIT (Just-In-Time) and AOT (Ahead-Of-Time) are compilation techniques used in Angular.
  • JIT compilation occurs at runtime, where the Angular compiler runs in the browser and compiles the application's code.
  • AOT compilation happens during the build process, where the Angular compiler converts the application's code into efficient JavaScript code before deployment.

Example Code:


// JIT compilation
ng serve

// AOT compilation
ng build --prod

16. Angular lifecycle hooks - ngOninit and Constructor which will call first

Description:

  • Angular components have a lifecycle that consists of various stages.
  • The constructor is called first when a component is instantiated.
  • ngOnInit is called after the constructor and after Angular has initialized the component's data-bound properties.

Example Code:


export class MyComponent implements OnInit {
  constructor() {
    console.log('Constructor called');
  }

  ngOnInit() {
    console.log('ngOnInit called');
  }
}

17. ngOnchanges and other events

Description:

  • ngOnChanges is a lifecycle hook in Angular that is called when the input properties of a component change.
  • Other events in Angular include ngOnInit, ngAfterViewInit, ngOnDestroy, etc., which correspond to different stages in the component lifecycle.

Example Code:


export class MyComponent implements OnChanges {
  ngOnChanges(changes: SimpleChanges) {
    // Logic to handle changes in input properties
  }
}

18. Bootstrap and its uses

Description:

  • Bootstrap is a popular CSS framework for building responsive and mobile-first web applications.
  • It provides pre-styled components and utilities for layout, typography, forms, buttons, and more.
  • Bootstrap makes it easy to create modern and visually appealing user interfaces.

Example Code:


<!-- Example usage of Bootstrap grid system -->
<div class="container">
  <div class="row">
    <div class="col-md-6">
      <p>Content goes here</p>
    </div>
    <div class="col-md-6">
      <p>Content goes here</p>
    </div>
  </div>
</div>

19. Differences between JS and Angular

Description:

  • JavaScript (JS) is a programming language used for creating dynamic and interactive web pages.
  • Angular is a TypeScript-based open-source web application framework developed by Google for building single-page applications (SPAs).
  • While JavaScript is the language itself, Angular is a framework built on top of JavaScript that provides structure and features for building complex web applications.

20. Grids- ag-grid, mat-tab, kendo-grid - its merits and demerits

Description:

  • ag-Grid: ag-Grid is a feature-rich datagrid for Angular applications. It offers a wide range of features and customization options but may be more complex to set up.
  • mat-table: mat-table is part of Angular Material, providing a clean and simple table implementation with Material Design styling. It's easy to use and integrates well with other Angular Material components.
  • kendo-grid: kendo-grid is part of the Kendo UI library, offering a comprehensive set of features and support for various data sources. However, it comes with a licensing cost and may be overkill for simpler applications.

Example Code:



<ag-grid-angular
    style="width: 100%; height: 500px;"
    class="ag-theme-alpine"
    [rowData]="rowData"
    [columnDefs]="columnDefs">
</ag-grid-angular>


<table mat-table [dataSource]="dataSource">
    <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>


<kendo-grid [data]="gridData">
    <kendo-grid-column field="ProductName" title="Product Name"></kendo-grid-column>
    <kendo-grid-column field="UnitPrice" title="Price"></kendo-grid-column>
</kendo-grid>

Additional Questions

1. ngRx state management - reducers, state...

Description:

  • ngRx is a state management library for Angular applications, inspired by Redux.
  • It utilizes concepts such as actions, reducers, and effects to manage application state in a predictable and immutable way.
  • Reducers are pure functions responsible for handling state transitions based on dispatched actions.
  • The state represents the current state of the application, which is managed by reducers.

Example Code:


// Example reducer
function reducer(state = initialState, action: Action): State {
  switch (action.type) {
    case ActionTypes.LoadDataSuccess:
      return { ...state, data: action.payload };
    default:
      return state;
  }
}