Prepare for Angular Interviews with Over 110+ Essential Concepts

Prepare for Angular Interviews with Over 110+ Essential Concepts

Get interview-ready with these 110+ Angular concepts

1. What is Angular?

Answer: Angular is a platform for building client-side applications using TypeScript, HTML, and CSS. It provides powerful tools like routing, forms, HTTP handling, and dependency injection.

Code:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular App';
}

2. What is a Component in Angular?

Answer: A component in Angular is a building block that encapsulates a view (HTML) and its associated behavior (logic).

Code:

@Component({
  selector: 'app-user',
  template: `<h1>{{ name }}</h1>`,
  styleUrls: ['./user.component.css']
})
export class UserComponent {
  name = 'John Doe';
}

3. What is a Module in Angular?

Answer: A module is a container for components, services, pipes, and directives. The root module is AppModule.

Code:

@NgModule({
  declarations: [AppComponent, UserComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

4. What is a Service in Angular?

Answer: A service is a class that handles business logic, HTTP requests, or other functionalities. It is injected into components via Dependency Injection (DI).

Code:

@Injectable({
  providedIn: 'root'
})
export class UserService {
  getUser() {
    return { name: 'John Doe', age: 25 };
  }
}

5. What is Dependency Injection (DI) in Angular?

Answer: DI is a design pattern where dependencies (services) are injected into a class instead of being created by it.

Code:

@Component({
  selector: 'app-root',
  template: '<h1>{{ user.name }}</h1>'
})
export class AppComponent {
  constructor(private userService: UserService) {}
  user = this.userService.getUser();
}

6. What is a Directive in Angular?

Answer: Directives are used to manipulate the DOM elements (structure, behavior, or appearance) in Angular.

Code:

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}

7. What is a Pipe in Angular?

Answer: A pipe transforms data in the view, such as formatting dates or filtering lists.

Code:

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}

8. What is Angular CLI?

Answer: Angular CLI is a command-line interface that automates common tasks like creating components, services, testing, and deployment.

Command:

ng generate component my-component
ng serve

9. What is Two-Way Data Binding in Angular?

Answer: Two-way data binding synchronizes data between the model and the view, achieved using [(ngModel)].

Code:

<input [(ngModel)]="name">
<p>{{ name }}</p>

10. What is One-Way Data Binding in Angular?

Answer: One-way data binding allows data to flow in one direction, either from component to view or view to component.

Code:

<!-- From Component to View -->
<p>{{ name }}</p>

<!-- From View to Component -->
<input [value]="name">

11. What is a Template in Angular?

Answer: A template defines the view for the component. It can include Angular directives, data bindings, and expressions.

Code:

<h1>{{ title }}</h1>
<button (click)="changeTitle()">Change Title</button>

12. What is the ngOnInit Lifecycle Hook?

Answer: The ngOnInit lifecycle hook is called after Angular has initialized the input properties of a component.

Code:

ngOnInit() {
  console.log('Component initialized');
}

13. What is the ngOnDestroy Lifecycle Hook?

Answer: The ngOnDestroy lifecycle hook is called when a component is destroyed. It is used for cleanup tasks.

Code:

ngOnDestroy() {
  console.log('Component destroyed');
}

14. What is Routing in Angular?

Answer: Routing allows navigation between different views or components based on URL changes.

Code:

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

15. What is a Route Guard in Angular?

Answer: Route guards are services that protect routes based on conditions like user authentication.

Code:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

16. What is Angular Forms Module?

Answer: Angular Forms is used to handle user inputs. It provides Template-driven and Reactive forms.

Code:

<!-- Template-driven form -->
<form #form="ngForm">
  <input name="username" ngModel>
</form>

<!-- Reactive form -->
form = this.fb.group({
  username: ['']
});

17. What is RxJS in Angular?

Answer: RxJS (Reactive Extensions for JavaScript) is a library for handling asynchronous data streams in Angular, primarily used with Observables.

Code:

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  observer.next('Hello');
  observer.complete();
});

18. What are Observables in Angular?

Answer: Observables represent a stream of asynchronous events, providing methods to subscribe and handle emitted values.

Code:

import { Observable } from 'rxjs';

this.dataService.getData().subscribe(data => {
  console.log(data);
});

19. What is HttpClientModule in Angular?

Answer: HttpClientModule is used for making HTTP requests in Angular.

Code:

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

@NgModule({
  imports: [HttpClientModule]
})
export class AppModule {}

20. How do you make a GET request in Angular?

Answer: You can use the HttpClient service to make GET requests.

Code:

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

constructor(private http: HttpClient) {}

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

21. What is a Template-driven Form in Angular?

Answer: Template-driven forms are forms that are defined in the component’s template using Angular directives. They are easier to implement for simple forms.

Code:

<form #form="ngForm" (ngSubmit)="onSubmit(form)">
  <input name="username" ngModel>
  <button type="submit">Submit</button>
</form>

22. What is a Reactive Form in Angular?

Answer: Reactive forms are defined in the component class and use FormControl and FormGroup to manage form state and validation.

Code:

import { FormBuilder, FormGroup } from '@angular/forms';

export class AppComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      username: ['']
    });
  }

  onSubmit() {
    console.log(this.form.value);
  }
}

23. What is a FormControl in Angular?

Answer: A FormControl is used to track the value and validation status of a form control in Angular's reactive forms.

Code:

import { FormControl } from '@angular/forms';

this.username = new FormControl('');  // FormControl initialization

24. What is a FormGroup in Angular?

Answer: A FormGroup is a collection of FormControl instances that track the value and validation status of a form's controls.

Code:

import { FormGroup, FormBuilder } from '@angular/forms';

this.form = this.fb.group({
  username: [''],
  password: ['']
});

25. What is a Pipe in Angular?

Answer: A pipe is a function that takes an input value and transforms it to a desired output format.

Code:

@Pipe({ name: 'currency' })
export class CurrencyPipe implements PipeTransform {
  transform(value: number): string {
    return '$' + value.toFixed(2);
  }
}

26. What is the AsyncPipe in Angular?

Answer: The AsyncPipe automatically subscribes to an observable or promise and returns the latest value. It is commonly used to handle asynchronous data.

Code:

<div *ngIf="data$ | async as data">
  {{ data }}
</div>

27. What is Lazy Loading in Angular?

Answer: Lazy loading is a technique in Angular where modules are loaded on demand, improving the initial loading time of the application.

Code:

const routes: Routes = [
  { path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) }
];

28. What is AOT (Ahead-of-Time) Compilation in Angular?

Answer: AOT is a build process where Angular templates and TypeScript code are compiled during build time, leading to faster rendering at runtime.


29. What is JIT (Just-in-Time) Compilation in Angular?

Answer: JIT is a compilation process where Angular templates and TypeScript code are compiled in the browser at runtime.


30. What is an Observable in Angular?

Answer: An Observable is a stream that allows you to work with asynchronous data. It can be used to handle HTTP requests, user input events, etc.

Code:

import { Observable } from 'rxjs';

this.http.get('https://api.example.com').subscribe(data => {
  console.log(data);
});

31. What is a Subject in Angular?

Answer: A Subject is a type of observable that allows values to be multicasted to multiple observers. It can both emit values and subscribe to them.

Code:

import { Subject } from 'rxjs';

const subject = new Subject<number>();
subject.subscribe(value => console.log(value));
subject.next(1);
subject.next(2);

32. What is an EventEmitter in Angular?

Answer: EventEmitter is used to emit events from a child component to its parent component.

Code:

import { EventEmitter, Output } from '@angular/core';

@Output() eventOccurred = new EventEmitter<string>();

triggerEvent() {
  this.eventOccurred.emit('Event triggered');
}

33. What is the ChangeDetectionStrategy in Angular?

Answer: ChangeDetectionStrategy defines how Angular should check for changes in the component. It can be set to Default or OnPush for optimization.

Code:

@Component({
  selector: 'app-component',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {}

34. What is the NgIf Directive in Angular?

Answer: The NgIf directive is used to conditionally include or exclude a template from the DOM based on a boolean expression.

Code:

<div *ngIf="isVisible">Content visible</div>

35. What is the NgFor Directive in Angular?

Answer: The NgFor directive is used to loop through a collection and render a template for each item in the collection.

Code:

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

36. What is the NgClass Directive in Angular?

Answer: The NgClass directive is used to add or remove CSS classes conditionally.

Code:

<div [ngClass]="{ 'active': isActive, 'inactive': !isActive }">Toggle Class</div>

37. What is the NgStyle Directive in Angular?

Answer: The NgStyle directive is used to set inline styles dynamically.

Code:

<div [ngStyle]="{ 'color': color, 'font-size': fontSize }">Styled Text</div>

38. What is Event Binding in Angular?

Answer: Event binding is used to listen to events such as click, submit, and keyup and call a method or expression when the event occurs.

Code:

<button (click)="onClick()">Click Me</button>

39. What is Property Binding in Angular?

Answer: Property binding is used to bind a component property to an HTML element property.

Code:

<img [src]="imageSrc" alt="Dynamic Image">

40. What is the Role of @Injectable in Angular?

Answer: The @Injectable decorator marks a class as available for dependency injection. It is used in services or other injectables.

Code:

@Injectable({
  providedIn: 'root'
})
export class MyService {}

41. What are HttpHeaders in Angular?

Answer: HttpHeaders are used to add custom headers to HTTP requests in Angular.

Code:

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

const headers = new HttpHeaders().set('Authorization', 'Bearer token');

42. What is the ActivatedRoute in Angular?

Answer: ActivatedRoute provides access to the current route and its parameters.

Code:

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  const id = this.route.snapshot.paramMap.get('id');
  console.log(id);
}

Answer: RouterLink is used to bind a route to a clickable element, enabling navigation to the corresponding route.

Code:

<a [routerLink]="['/home']">Home</a>

44. What is the RouterOutlet Directive in Angular?

Answer: RouterOutlet acts as a placeholder where the routed component is displayed.

Code:

<router-outlet></router-outlet>

45. What is a Dynamic Component in Angular?

Answer: Dynamic components are components that are created and inserted into the view at runtime.

Code:

import { ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';

@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

createComponent() {
  const factory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent);
  this.container.createComponent(factory);
}

46. What is the Renderer2 Service in Angular?

Answer: Renderer2 is a service used to modify the DOM in a platform-independent way, particularly for elements that need to be manipulated.

Code:

constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit() {
  this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
}

47. What are Guards in Angular?

Answer: Guards are services that can be used to protect routes by restricting access based on conditions (e.g., user authentication).

Code:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService) {}

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

48. What is the @Input Decorator in Angular?

Answer: @Input allows a parent component to pass data to a child component.

Code:

@Component({
  selector: 'app-child',
  template: `<p>{{ message }}</p>`
})
export class ChildComponent {
  @Input() message: string;
}

49. What is the @Output Decorator in Angular?

Answer: @Output is used to create custom events that a child component can emit to the parent component.

Code:

@Output() eventOccurred = new EventEmitter<string>();

triggerEvent() {
  this.eventOccurred

.emit('Event triggered'); }


---

### 50. **What is the OnInit Lifecycle Hook in Angular?**
**Answer:** `OnInit` is a lifecycle hook that is called after Angular has initialized all data-bound properties.

**Code:**
```typescript
ngOnInit() {
  console.log('Component initialized');
}

51. What is the ngOnChanges Lifecycle Hook in Angular?

Answer: ngOnChanges is a lifecycle hook that is triggered whenever there is a change in the input properties of a component. It’s useful for reacting to changes in input data.

Code:

ngOnChanges(changes: SimpleChanges) {
  for (let propName in changes) {
    let change = changes[propName];
    console.log(`${propName}: ${change.currentValue}`);
  }
}

52. What is the ngDoCheck Lifecycle Hook in Angular?

Answer: ngDoCheck is a lifecycle hook that is called during every change detection cycle, allowing you to implement custom change detection.

Code:

ngDoCheck() {
  console.log('Change detection cycle executed');
}

53. What is the ngAfterViewInit Lifecycle Hook in Angular?

Answer: ngAfterViewInit is called after Angular initializes the component's views and child views. It’s useful when you need to interact with the view after it has been fully initialized.

Code:

ngAfterViewInit() {
  console.log('View initialized');
}

54. What is the ngAfterViewChecked Lifecycle Hook in Angular?

Answer: ngAfterViewChecked is invoked after Angular checks the component’s views and child views. It allows you to react to changes after the view has been checked.

Code:

ngAfterViewChecked() {
  console.log('View checked');
}

55. What is the ngOnDestroy Lifecycle Hook in Angular?

Answer: ngOnDestroy is used to clean up resources and unsubscribe from observables or detach event listeners before a component or directive is destroyed.

Code:

ngOnDestroy() {
  console.log('Component destroyed');
}

56. What is the difference between ngOnInit and ngAfterViewInit?

Answer: ngOnInit is called after the component’s data-bound properties are initialized, while ngAfterViewInit is called after the component’s view and its children are initialized.


57. What are Angular Modules (NgModules)?

Answer: An Angular module (NgModule) is a container that groups related components, services, and other code together. It defines a compilation context for components and a dependency injection context for services.

Code:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

58. What is the providedIn Property in Angular Services?

Answer: The providedIn property allows you to specify where the service should be available, such as root for application-wide availability or a specific module for limited scope.

Code:

@Injectable({
  providedIn: 'root'
})
export class MyService {}

59. What is the @HostListener Decorator in Angular?

Answer: @HostListener allows you to listen to events on the host element of a component or directive.

Code:

@HostListener('window:resize', ['$event'])
onResize(event) {
  console.log('Window resized', event.target.innerWidth);
}

60. What is the @HostBinding Decorator in Angular?

Answer: @HostBinding binds a property or attribute of the host element to a property in the component.

Code:

@HostBinding('style.backgroundColor') backgroundColor: string = 'lightblue';

61. What is the Role of ng-content in Angular?

Answer: ng-content is used in Angular to project content into a component’s view from the outside.

Code:

<app-child>
  <div>Projected Content</div>
</app-child>

Child Component Template:

<ng-content></ng-content>

62. What is the ChangeDetectorRef Service in Angular?

Answer: ChangeDetectorRef provides methods to control the change detection mechanism manually, such as detecting changes outside the Angular zone or triggering change detection explicitly.

Code:

import { ChangeDetectorRef } from '@angular/core';

constructor(private cdr: ChangeDetectorRef) {}

triggerChangeDetection() {
  this.cdr.detectChanges();
}

63. What is the Angular zone.js Library?

Answer: zone.js is a library used by Angular to manage asynchronous operations (like HTTP requests, event handling, etc.) and trigger change detection when those operations complete.


64. What are Template Reference Variables in Angular?

Answer: Template reference variables allow you to reference DOM elements, child components, or directives within a template and interact with them in the component class.

Code:

<input #inputElement />
<button (click)="inputElement.focus()">Focus</button>

65. What is the difference between ngFor and ngForOf in Angular?

Answer: Both directives are used for iterating over collections, but ngForOf is the correct and preferred syntax, while ngFor is shorthand for ngForOf with the of keyword.

Code:

<!-- ngFor -->
<li *ngFor="let item of items">{{ item }}</li>

<!-- ngForOf -->
<li *ngFor="let item of items">{{ item }}</li>

66. What is the ng-template Directive in Angular?

Answer: ng-template is used to define a block of HTML that is not rendered until it is referenced elsewhere in the template.

Code:

<ng-template #templateRef>
  <p>This is a template.</p>
</ng-template>
<button (click)="viewTemplate()">View Template</button>

67. What is the ng-container in Angular?

Answer: ng-container is a structural directive that allows grouping elements without adding extra DOM nodes.

Code:

<ng-container *ngIf="isVisible">
  <p>This will be conditionally rendered.</p>
</ng-container>

68. What is Angular Material?

Answer: Angular Material is a UI component library that provides pre-built, customizable, and responsive components based on Google's Material Design principles.

Code:

import { MatButtonModule } from '@angular/material/button';

@NgModule({
  imports: [MatButtonModule],
})
export class AppModule {}

69. What is a Custom Pipe in Angular?

Answer: A custom pipe allows you to create reusable data transformation logic that can be used in templates.

Code:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}

70. What is a Singleton Service in Angular?

Answer: A singleton service is a service that is instantiated only once throughout the application, usually provided in the root scope. This ensures that the service has a single shared instance across the app.

Code:

@Injectable({
  providedIn: 'root'
})
export class SingletonService {
  getData() {
    return 'Shared Data';
  }
}

71. What is the Difference Between Observable and Promise in Angular?

Answer: Both Observable and Promise are used for asynchronous operations, but:

  • Observable can emit multiple values over time.

  • Promise emits a single value or an error once.


72. What is an HttpInterceptor in Angular?

Answer: An HttpInterceptor is used to intercept HTTP requests and responses to modify or log them before they are handled.

Code:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      headers: req.headers.set('Authorization', 'Bearer token')
    });
    return next.handle(clonedRequest);
  }
}

73. What are Angular Directives?

Answer: Directives are classes that allow you to manipulate the DOM by either changing the appearance or behavior of elements or applying logic to templates.


74. What is Lazy Loading in Angular?

Answer: Lazy loading is a design pattern that allows modules to be loaded on demand rather than at the start of the application. This helps improve the application’s startup time by loading only the necessary modules initially.

Code:

const routes: Routes = [
  { path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];

75. What is the CanActivate Guard in Angular?

Answer: The CanActivate guard is used to prevent unauthorized access to routes. It is implemented as a service that returns a boolean or an observable that determines if the route can be activated.

Code:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

76. What is the CanDeactivate Guard in Angular?

Answer: The CanDeactivate guard is used to prevent users from navigating away from a route if they have unsaved changes. It returns a boolean or an observable based on whether the user is allowed to navigate away.

Code:

@Injectable({
  providedIn: 'root'
})
export class UnsavedChangesGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

77. What is ngOnInit vs. ngAfterViewInit Lifecycle Hook in Angular?

Answer:

  • ngOnInit is invoked once when the component is initialized.

  • ngAfterViewInit is invoked after the component’s view and child views have been initialized, and it's useful for interacting with the view.


78. What is ng-content in Angular?

Answer: ng-content is used to project content from a parent component into a child component. It is useful for creating reusable components that allow content to be injected.

Code:

<ng-content></ng-content>

79. What is the ng-template Directive in Angular?

Answer: ng-template is used for defining an inline template that can be conditionally rendered in a component. It doesn’t render the content until it is referenced elsewhere in the component template.

Code:

<ng-template #myTemplate>
  <p>This is a template content</p>
</ng-template>

<button (click)="viewTemplate()">View Template</button>

80. What is the ngClass Directive in Angular?

Answer: ngClass is used to dynamically apply CSS classes to an element based on the conditions in the component class. You can pass an object, array, or string to ngClass to control the classes.

Code:

<div [ngClass]="{ 'highlight': isHighlighted }">This text is conditionally highlighted</div>

81. What is the ngStyle Directive in Angular?

Answer: ngStyle is used to dynamically set CSS styles for an element based on the component’s state.

Code:

<div [ngStyle]="{ 'color': color, 'font-size': fontSize }">Styled text</div>

82. What is the Difference Between ngModel and formControl in Angular?

Answer:

  • ngModel is used for two-way data binding in template-driven forms.

  • formControl is used for reactive forms to control the value and validation of form inputs.


83. What are Angular Reactive Forms?

Answer: Reactive forms are more scalable, robust, and flexible than template-driven forms. They are built using FormGroup, FormControl, and FormArray to manage form controls in the component class.

Code:

import { FormGroup, FormControl } from '@angular/forms';

export class AppComponent {
  form = new FormGroup({
    name: new FormControl(''),
    email: new FormControl(''),
  });
}

84. What is FormBuilder in Angular?

Answer: FormBuilder is a service that simplifies the creation of reactive forms by providing methods to easily create form groups and form controls.

Code:

import { FormBuilder, FormGroup } from '@angular/forms';

export class AppComponent {
  form: FormGroup;
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: [''],
      email: ['']
    });
  }
}

85. What is an HttpClient in Angular?

Answer: HttpClient is a service that provides methods for making HTTP requests, such as GET, POST, PUT, and DELETE. It is part of the @angular/common/http package and supports working with Observables.

Code:

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

constructor(private http: HttpClient) {}

getData() {
  this.http.get('https://api.example.com/data').subscribe(data => {
    console.log(data);
  });
}

86. What is the HttpHeaders in Angular?

Answer: HttpHeaders is used to set custom HTTP headers when making HTTP requests using the HttpClient.

Code:

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

const headers = new HttpHeaders().set('Authorization', 'Bearer token');
this.http.get('https://api.example.com/data', { headers }).subscribe(data => {
  console.log(data);
});

87. What is the HttpInterceptor in Angular?

Answer: HttpInterceptor allows you to intercept HTTP requests and responses to modify or log them before they are handled. It can be used for adding authorization headers, logging, or handling errors.

Code:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      setHeaders: {
        Authorization: `Bearer token`
      }
    });
    return next.handle(clonedRequest);
  }
}

88. What is Angular Change Detection?

Answer: Angular’s change detection is the process that checks for changes in the application’s model and updates the view accordingly. It is triggered automatically when events like HTTP requests, user inputs, or timers change the state of the component.


89. What are Angular Pipes?

Answer: Pipes are used to transform data in Angular templates. They can format data or change its structure before displaying it to the user.

Code:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'reverse'
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}

90. What is ngZone in Angular?

Answer: ngZone is used to manage the Angular change detection and to run certain operations outside of the Angular zone. This is helpful in performance optimization when handling operations that don't require Angular to check the model.

Code:

import { NgZone } from '@angular/core';

constructor(private zone: NgZone) {}

runOutsideAngular() {
  this.zone.runOutsideAngular(() => {
    console.log('This is outside Angular zone');
  });
}

91. What is the Difference Between ngFor and ngIf?

Answer:

  • ngFor is used to iterate over a list or collection of items and render elements for each item.

  • ngIf is used to conditionally include or exclude an element based on a boolean expression.


92. What is the Renderer2 Service in Angular?

Answer: Renderer2 provides an abstraction for DOM manipulation. It is used to safely interact with the DOM without directly accessing it, which improves security and compatibility.

Code:

import { Renderer2, ElementRef } from '@angular/core';

constructor(private renderer: Renderer2, private el: ElementRef) {}

changeBackgroundColor() {
  this.renderer.setStyle(this.el.nativeElement, 'background-color', 'blue');
}

Here are more Angular concepts with interview-style questions, answers, and code snippets:


93. What is the ngOnChanges Lifecycle Hook in Angular?

Answer: ngOnChanges is a lifecycle hook that is called when an input property of a component changes. It is useful for detecting changes in input properties and reacting to them.

Code:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<p>{{data}}</p>`
})
export class ChildComponent implements OnChanges {
  @Input() data: string;

  ngOnChanges(changes: SimpleChanges) {
    console.log('Data changed:', changes.data);
  }
}

94. What is Dependency Injection in Angular?

Answer: Dependency Injection (DI) is a design pattern used in Angular to provide services and objects to components, ensuring better modularity and testability. It is handled by Angular’s injector.

Code:

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() {}
}

@Component({
  selector: 'app-my-component',
  template: `<p>Service injected!</p>`
})
export class MyComponent {
  constructor(private myService: MyService) {}
}

95. What is an Angular Service?

Answer: An Angular service is a class that provides logic for data management, business rules, and interaction with external APIs. It is typically injected into components or other services.


96. What is the @Injectable Decorator in Angular?

Answer: @Injectable is a decorator used to define a class as injectable, which means it can be used as a service and injected into other components or services.

Code:

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

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

97. What is a Module in Angular?

Answer: A module in Angular is a container for components, services, directives, pipes, and other modules. It organizes the application into cohesive blocks and is defined by the @NgModule decorator.

Code:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

98. What is ngForOf in Angular?

Answer: ngForOf is a structural directive used to repeat a part of the HTML template for each item in a list or array. It is the most commonly used loop in Angular templates.

Code:

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

99. What is ngIf Else Syntax in Angular?

Answer: ngIf else syntax is used for conditional rendering, where one template is displayed if the condition is true and another is displayed if false.

Code:

<div *ngIf="isLoggedIn; else loginTemplate">
  Welcome, User!
</div>
<ng-template #loginTemplate>
  Please log in to continue.
</ng-template>

100. What are Angular Directives?

Answer: Directives are special markers attached to elements in the DOM that change the element’s behavior or appearance. There are three types of directives: structural, attribute, and component directives.

  • Structural Directives: Modify the structure of the DOM, such as *ngIf and *ngFor.

  • Attribute Directives: Modify the appearance or behavior of DOM elements, such as ngClass and ngStyle.

  • Component Directives: Create new HTML elements, such as custom components.


101. What is the Difference Between ngOnInit and ngAfterContentInit?

Answer:

  • ngOnInit is called once after the first ngOnChanges and is used to initialize the component or directive.

  • ngAfterContentInit is called after the content (the projected content) has been initialized.


102. What is the ngZone Service in Angular?

Answer: ngZone provides a way to interact with the Angular change detection mechanism and allows you to run code outside the Angular zone to improve performance. It helps manage the detection cycles manually.

Code:

import { NgZone } from '@angular/core';

constructor(private zone: NgZone) {}

runOutsideAngular() {
  this.zone.runOutsideAngular(() => {
    setTimeout(() => {
      console.log('Code executed outside Angular zone');
    }, 1000);
  });
}

103. What is ngModel in Angular?

Answer: ngModel is a directive that provides two-way data binding between the DOM and the component. It helps to bind input fields to component properties and vice versa.

Code:

<input [(ngModel)]="name" />
<p>{{ name }}</p>

104. What is the ng-template Directive in Angular?

Answer: ng-template is used to define a block of HTML code that is not rendered by default. It can be conditionally rendered based on the logic in the component.

Code:

<ng-template #template>
  <div>This is a template content</div>
</ng-template>

105. What is a Route Guard in Angular?

Answer: A route guard is a feature in Angular that helps manage navigation decisions. Guards can be used to protect routes from unauthorized access, prevent navigation if there are unsaved changes, or control route redirection.


106. What is ActivatedRoute in Angular?

Answer: ActivatedRoute is a service used to access the route information for the active route, including route parameters, query parameters, and more.

Code:

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {
  this.route.params.subscribe(params => {
    console.log(params['id']);
  });
}

Answer: RouterLink is a directive used to navigate to a different route when clicked. It binds the navigation to the href property of an anchor tag.

Code:

<a [routerLink]="['/home']">Go to Home</a>

108. What is the RouterLinkActive Directive in Angular?

Answer: RouterLinkActive is a directive used to add or remove CSS classes when the associated route is active.

Code:

<a [routerLink]="['/home']" routerLinkActive="active">Go to Home</a>

109. What is ngOnDestroy Lifecycle Hook in Angular?

Answer: ngOnDestroy is called when a component or directive is destroyed. It is typically used to unsubscribe from observables, remove event listeners, or perform other cleanup operations.

Code:

import { OnDestroy } from '@angular/core';

export class MyComponent implements OnDestroy {
  ngOnDestroy() {
    console.log('Component destroyed!');
  }
}

110. What is Angular CLI and What are its Benefits?

Answer: Angular CLI (Command Line Interface) is a tool used to automate the process of creating, building, and maintaining Angular applications. It provides commands to generate components, services, modules, and more.

Common Commands:

ng new my-app      # Create a new Angular application
ng serve           # Start the development server
ng generate component component-name  # Generate a component
ng build           # Build the app for production

111. What is HttpClientModule in Angular?

Answer: HttpClientModule is a module in Angular used to make HTTP requests. It needs to be imported in the AppModule to use the HttpClient service.

Code:

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

@NgModule({
  imports: [HttpClientModule]
})
export class AppModule {}

Did you find this article valuable?

Support CodeWords by becoming a sponsor. Any amount is appreciated!