Angular Interview Questions

Angular Interview Questions - Components & Templates (31-60)

Master Angular components and templates for FAANG interviews: content projection, component communication, view encapsulation, and more with examples.

By TechCoder TeamLast updated: 2026-06-15
In a Nutshell

Master Angular components and templates for FAANG interviews: content projection, component communication, view encapsulation, and more with examples. This interview-focused guide covers essential angular interview questions - components & templates (31-60) concepts for technical interviews.

Angular Interview Questions - Components & Templates (31-60)

Question 31: What is Content Projection (ng-content)?

Content projection allows you to insert content from a parent component into a child component's template using <ng-content>.

Example:

// card.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-card',
  template: `
    <div class="card">
      <ng-content select="[header]"></ng-content>
      <hr>
      <ng-content select="[body]"></ng-content>
      <hr>
      <ng-content select="[footer]"></ng-content>
    </div>
  `,
  standalone: true
})
export class CardComponent {}

// parent component template
<app-card>
  <div header>Card Header</div>
  <div body>Card Body Content</div>
  <div footer>Card Footer</div>
</app-card>

Question 32: What is View Encapsulation?

View encapsulation defines how Angular styles apply to components and the rest of the DOM. There are 3 types:

TypeDescription
ViewEncapsulation.EmulatedDefault! Scopes styles to component (adds attribute like _ngcontent-abc123).
ViewEncapsulation.ShadowDomUses browser Shadow DOM API (true encapsulation).
ViewEncapsulation.NoneNo encapsulation, styles leak to entire DOM!

Example:

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-encapsulated',
  template: `<p>Encapsulated text</p>`,
  styles: [`p { color: blue; }`],
  encapsulation: ViewEncapsulation.Emulated // Default
})
export class EncapsulatedComponent {}

Question 33: What is a Template Reference Variable?

Template variables let you reference elements/directives/components in the template with a # prefix!

Example:

<input #nameInput type="text" placeholder="Enter name">
<button (click)="logValue(nameInput.value)">Log Value</button>

<p>{{ nameInput.value }}</p>

Question 34: What are Template Statements?

Template statements respond to events in templates (like (click)="doSomething()"). They can use component properties, methods, operators, etc.!

Example:

@Component({
  selector: 'app-statements',
  template: `
    <button (click)="increment()">Count: {{ count }}</button>
  `,
  standalone: true
})
export class StatementsComponent {
  count = 0;
  increment() { this.count++; }
}

Question 35: What are Template Expressions?

Template expressions produce a value and are used in property bindings and interpolations! They should be idempotent (no side effects) and fast!

Example:

<p>{{ title + ' - 2025' }}</p>
<p>{{ price * (1 + taxRate) | currency }}</p>
<p>{{ isLoggedIn ? 'Welcome back!' : 'Please log in' }}</p>

Question 36: What are Angular @HostBinding and @HostListener Decorators?

  • @HostBinding: Lets you bind to a host element property
  • @HostListener: Lets you listen to events on a host element

Example:

import { Directive, HostBinding, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  @HostBinding('style.backgroundColor') bgColor!: string;

  @HostListener('mouseenter') onMouseEnter() {
    this.bgColor = 'yellow';
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.bgColor = 'transparent';
  }
}

// Usage in template
<p appHighlight>Hover me to highlight!</p>

Question 37: What is an Attribute Directive vs Structural Directive?

  • Attribute Directive: Changes appearance/behavior of an element (e.g., ngClass, ngStyle, custom directives)
  • Structural Directive: Changes DOM structure by adding/removing elements (starts with *, e.g., *ngIf, *ngFor)

Question 38: What is the async Pipe?

The async pipe subscribes to an Observable or Promise and returns the latest emitted value! It also automatically unsubscribes to prevent memory leaks!

Example:

import { Component } from '@angular/core';
import { Observable, interval, map } from 'rxjs';
import { AsyncPipe, CommonModule } from '@angular/common';

@Component({
  selector: 'app-async-pipe',
  template: `
    <p>Count: {{ count$ | async }}</p>
  `,
  standalone: true,
  imports: [AsyncPipe, CommonModule]
})
export class AsyncPipeComponent {
  count$: Observable<number> = interval(1000).pipe(map(i => i));
}

Question 39: What is ng-template?

<ng-template> is an Angular element that doesn't render anything by itself - it needs to be rendered conditionally by a structural directive like *ngIf, *ngFor, or using a directive like ViewContainerRef!

Example:

<div *ngIf="isLoggedIn; else loggedOut">
  Welcome back!
</div>

<ng-template #loggedOut>
  Please log in.
</ng-template>

Question 40: What is ng-container?

<ng-container> is a logical container that groups elements without adding an extra DOM element! Perfect for applying structural directives without adding bloat!

Example:

<!-- No extra div in DOM! -->
<ng-container *ngIf="isLoggedIn">
  <h1>Welcome</h1>
  <p>You are logged in!</p>
</ng-container>

Question 41: How do you communicate between parent and child components?

WayDirectionUse When
@Input()Parent → ChildPass data down
@Output() + EventEmitterChild → ParentEmit events up
ServiceBothShare data globally
@ViewChild/@ViewChildrenParent → ChildAccess child methods/props
@ContentChild/@ContentChildrenParent → ChildAccess projected content

Question 42: How do you communicate between sibling components?

  1. Use a shared service (best approach for non-trivial apps)
  2. Parent component as mediator (sibling → parent → sibling)

Shared Service Example:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class DataService {
  private dataSubject = new BehaviorSubject<string>('initial');
  data$ = this.dataSubject.asObservable();

  updateData(newData: string) {
    this.dataSubject.next(newData);
  }
}

Question 43: What is Component Interaction via a Service?

Components can communicate by subscribing to an Observable (usually a BehaviorSubject) in a shared service!


Question 44: What is ChangeDetectionStrategy?

Angular has two change detection strategies:

  1. Default: Checks all components on every async event
  2. OnPush: Only checks for changes if:
    • Input references change
    • Event is emitted from component or child
    • Manual ChangeDetectorRef.detectChanges() call

OnPush Example:

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

@Component({
  selector: 'app-on-push',
  template: `{{ user.name }}`,
  changeDetection: ChangeDetectionStrategy.OnPush, // Enable OnPush!
  standalone: true
})
export class OnPushComponent {
  @Input() user!: { name: string };
}

Question 45: What is ChangeDetectorRef?

ChangeDetectorRef is a service that gives you control over change detection! Methods:

  • detectChanges(): Manually trigger change detection
  • markForCheck(): Mark the component for check
  • detach(): Detach from CD tree
  • reattach(): Reattach to CD tree

Example:

import { Component, ChangeDetectorRef, OnInit } from '@angular/core';

@Component({
  selector: 'app-cd-ref',
  template: '{{ data }}',
  standalone: true
})
export class CdRefComponent implements OnInit {
  data = 'loading...';

  constructor(private cdRef: ChangeDetectorRef) {}

  ngOnInit() {
    setTimeout(() => {
      this.data = 'loaded!';
      this.cdRef.detectChanges(); // Manually trigger CD!
    }, 2000);
  }
}

Question 46: What are Angular Pure and Impure Pipes?

  • Pure Pipe: Only executes when the input reference or primitive value changes! (Default, recommended for performance!)
  • Impure Pipe: Executes on every change detection cycle! (Use sparingly!)

Example of Impure Pipe:

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

@Pipe({
  name: 'filter',
  pure: false // Mark as impure
})
export class FilterPipe implements PipeTransform {
  transform(list: any[], searchTerm: string): any[] {
    if (!list || !searchTerm) return list;
    return list.filter(item => item.name.toLowerCase().includes(searchTerm.toLowerCase()));
  }
}

Question 47: What is SafeValue and DomSanitizer?

DomSanitizer prevents XSS attacks by sanitizing values before binding them to innerHTML, src, etc.! You can mark values as safe with bypassSecurityTrustHtml(), bypassSecurityTrustUrl(), etc.!

Example:

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-sanitize',
  template: `<div [innerHtml]="safeHtml"></div>`,
  standalone: true
})
export class SanitizeComponent {
  safeHtml: SafeHtml;

  constructor(private sanitizer: DomSanitizer) {
    const unsafeHtml = '<h1>Hello <script>alert("xss")</script></h1>';
    this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(unsafeHtml);
  }
}

Question 48: What are Attribute vs Structural Directives?

  • Attribute: Change element's appearance/behavior ([ngStyle], [ngClass], custom directives with [selector])
  • Structural: Change DOM structure (*ngIf, *ngFor), use * syntax which desugars to <ng-template>

Question 49: How to Create a Custom Attribute Directive?

Use @Directive decorator! Let's make a directive that adds a border when clicked:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appBorder]',
  standalone: true
})
export class BorderDirective {
  @Input() appBorder = '2px solid red'; // Use directive name as input!

  constructor(private el: ElementRef) {}

  @HostListener('click') onClick() {
    this.el.nativeElement.style.border = this.appBorder;
  }
}

// Usage
<p appBorder="3px dashed blue">Click me for a border!</p>
<p appBorder>Default red border!</p>

Question 50: What is ElementRef?

ElementRef gives you direct access to the host DOM element via its nativeElement property! Use with caution (avoid direct DOM manipulation where possible)!


Question 51: What is Renderer2?

Renderer2 is a service that provides safe, platform-agnostic methods to modify the DOM! Prefer it over direct nativeElement manipulation!

Example:

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

@Directive({
  selector: '[appRenderer]',
  standalone: true
})
export class RendererDirective implements OnInit {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnInit() {
    this.renderer.setStyle(this.el.nativeElement, 'color', 'green');
    this.renderer.setAttribute(this.el.nativeElement, 'title', 'Hello from Renderer2!');
  }
}

Question 52: What is TemplateRef and ViewContainerRef?

  • TemplateRef: Represents an embedded template (ng-template)
  • ViewContainerRef: Represents a container where views can be attached!

Example (Structural Directive):

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appUnless]',
  standalone: true
})
export class UnlessDirective {
  private hasView = false;

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input() set appUnless(condition: boolean) {
    if (!condition && !this.hasView) {
      this.viewContainer.createEmbeddedView(this.templateRef);
      this.hasView = true;
    } else if (condition && this.hasView) {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }
}

// Usage
<p *appUnless="isHidden">I am visible unless isHidden is true!</p>

Question 53: What is *ngIf with else and then?

<div *ngIf="isLoggedIn; then loggedInTpl; else loggedOutTpl"></div>

<ng-template #loggedInTpl>Welcome back!</ng-template>
<ng-template #loggedOutTpl>Please log in!</ng-template>

Question 54: What is *ngFor Local Variables?

<ul>
  <li *ngFor="let product of products;
      index as i;
      first as isFirst;
      last as isLast;
      even as isEven;
      odd as isOdd">
    {{ i + 1 }}. {{ product.name }}
    <span *ngIf="isFirst"> (First!)</span>
  </li>
</ul>

Question 55: What is ngSwitch?

<div [ngSwitch]="status">
  <p *ngSwitchCase="'pending'">Pending</p>
  <p *ngSwitchCase="'approved'">Approved</p>
  <p *ngSwitchCase="'rejected'">Rejected</p>
  <p *ngSwitchDefault>Unknown status</p>
</div>

Question 56: What is ngStyle and ngClass?

<!-- ngClass -->
<div [ngClass]="{
  'active': isActive,
  'disabled': isDisabled,
  'error': hasError
}"></div>

<!-- ngStyle -->
<div [ngStyle]="{
  'color': isDark ? 'white' : 'black',
  'font-size': fontSize + 'px'
}"></div>

Question 57: What is Component Style Scope?

By default, component styles are emulated-scoped so they only affect that component's template elements! Use encapsulation to change this!


Question 58: What is host Metadata in Component Decorator?

You can set host element properties and listen to host events in the component decorator's host property!

@Component({
  selector: 'app-host-example',
  template: 'Hello',
  host: {
    '(click)': 'onHostClick()',
    '[class.active]': 'isActive',
    '[attr.role]': "'button'"
  }
})
export class HostExampleComponent {
  isActive = true;
  onHostClick() { console.log('Host clicked!'); }
}

Question 59: What are Angular Single File Components (SFCs)?

Angular components are usually split into 3 files: .ts, .html, .css. However, you can also write single-file components with template and styles properties in @Component (good for small components!)!


Question 60: What is the Difference Between ngOnInit and Constructor in Angular?

ConstructorngOnInit
Used to initialize class, inject dependenciesUsed to perform component initialization logic
Runs before component inputs are setRuns after inputs are set and view is initialized
Keep simple!Do data fetching, complex initialization here!