Angular Questions


Beginners To Experts


The site is under development.

Angular Cheat Sheets

Explanation: Components are the building blocks of Angular apps. Each component has a TypeScript class, an HTML template, and optionally CSS styles.

Syntax:

<component-selector></component-selector>
      

Example:

<!-- app.component.ts --><br>
import { Component } from '@angular/core';<br>
<br>
@Component({<br>
  selector: 'app-root',<br>
  template: '<h1>Hello Angular!</h1>'<br>
})<br>
export class AppComponent { }<br>
      

Explanation: Angular provides several data binding types: interpolation, property binding, event binding, and two-way binding to connect data between template and component.

Syntax:

Interpolation: {{ expression }}<br>
Property Binding: [property]="expression"<br>
Event Binding: (event)="handler()"<br>
Two-way Binding: [(ngModel)]="property"
      

Example:

<!-- app.component.html --><br>
<h2>Hello, {{name}}!</h2><br>
<input [value]="name" (input)="name = $event.target.value" /><br>
<input [(ngModel)]="name" placeholder="Enter your name" /><br>
      

Explanation: Directives add behavior to DOM elements. There are structural directives (like *ngIf, *ngFor) that change the layout, and attribute directives that change element appearance or behavior.

Syntax:

Structural: *ngIf="condition" <br>
Structural: *ngFor="let item of items" <br>
Attribute: [ngClass]="className" <br>
Attribute: [ngStyle]="styleObject"
      

Example:

<div *ngIf="isVisible">This is visible</div><br>
<ul><br>
  <li *ngFor="let user of users">{{ user.name }}</li><br>
</ul><br>
<div [ngClass]="{ 'highlight': isHighlighted }">Highlighted Text</div>
      

Explanation: Services are used to share data or logic across components. Dependency Injection (DI) is Angular's way to provide services to components efficiently.

Syntax:

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

constructor(private myService: MyService) { }
      

Example:

<!-- my.service.ts --><br>
import { Injectable } from '@angular/core';<br>
<br>
@Injectable({ providedIn: 'root' })<br>
export class MyService {<br>
  getValue() {<br>
    return 'Hello from Service!';<br>
  }<br>
}<br>
<br>
<!-- app.component.ts --><br>
import { Component } from '@angular/core';<br>
import { MyService } from './my.service';<br>
<br>
@Component({<br>
  selector: 'app-root',<br>
  template: '<h1>{{ message }}</h1>'<br>
})<br>
export class AppComponent {<br>
  message: string;<br>
  constructor(private myService: MyService) {<br>
    this.message = this.myService.getValue();<br>
  }<br>
}<br>
      

Explanation: Angular Router enables navigation between different views or components in a single-page app.

Syntax:

const routes: Routes = [<br>
  { path: 'home', component: HomeComponent },<br>
  { path: '', redirectTo: '/home', pathMatch: 'full' }<br>
];<br>

<router-outlet></router-outlet>
      

Example:

<!-- app-routing.module.ts --><br>
import { NgModule } from '@angular/core';<br>
import { RouterModule, Routes } from '@angular/router';<br>
import { HomeComponent } from './home/home.component';<br>
import { AboutComponent } from './about/about.component';<br>
<br>
const routes: Routes = [<br>
  { path: 'home', component: HomeComponent },<br>
  { path: 'about', component: AboutComponent },<br>
  { path: '', redirectTo: '/home', pathMatch: 'full' }<br>
];<br>
<br>
@NgModule({<br>
  imports: [RouterModule.forRoot(routes)],<br>
  exports: [RouterModule]<br>
})<br>
export class AppRoutingModule { }<br>
<br>
<!-- app.component.html --><br>
<nav><br>
  <a routerLink="/home">Home</a> |<br>
  <a routerLink="/about">About</a><br>
</nav><br>
<router-outlet></router-outlet>
      

Explanation: Angular supports two types of forms: Template-driven (simple forms in template) and Reactive forms (more powerful, defined in TS).

Syntax:

<!-- Template-driven --><br>
<form #form="ngForm"><br>
  <input name="username" ngModel required /><br>
  <button type="submit">Submit</button><br>
</form><br>

<!-- Reactive --><br>
this.myForm = this.fb.group({<br>
  username: ['', Validators.required]<br>
});
      

Example:

<!-- template-driven.component.html --><br>
<form #form="ngForm" (ngSubmit)="onSubmit(form)"><br>
  <input name="username" ngModel required placeholder="Username" /><br>
  <button type="submit">Submit</button><br>
</form><br>
<p>You entered: {{ username }}</p><br>

<!-- reactive.component.ts --><br>
import { Component } from '@angular/core';<br>
import { FormBuilder, FormGroup, Validators } from '@angular/forms';<br>
<br>
@Component({<br>
  selector: 'app-reactive-form',<br>
  templateUrl: './reactive.component.html'<br>
})<br>
export class ReactiveComponent {<br>
  myForm: FormGroup;<br>
  constructor(private fb: FormBuilder) {<br>
    this.myForm = this.fb.group({<br>
      username: ['', Validators.required]<br>
    });<br>
  }<br>
  onSubmit() {<br>
    console.log(this.myForm.value);<br>
  }<br>
}<br>
      

Explanation: Angular HttpClient module is used to communicate with backend services via HTTP requests such as GET, POST, PUT, DELETE.

Syntax:

this.http.get<Type>('api/url').subscribe(response => {<br>
  console.log(response);<br>
});

Example:

<!-- app.module.ts --><br>
import { HttpClientModule } from '@angular/common/http';<br>
@NgModule({<br>
  imports: [HttpClientModule]<br>
})<br>
export class AppModule { }<br>

<!-- data.service.ts --><br>
import { Injectable } from '@angular/core';<br>
import { HttpClient } from '@angular/common/http';<br>
import { Observable } from 'rxjs';<br>
<br>
@Injectable({ providedIn: 'root' })<br>
export class DataService {<br>
  constructor(private http: HttpClient) { }<br>
  getUsers(): Observable<any> {<br>
    return this.http.get('https://jsonplaceholder.typicode.com/users');<br>
  }<br>
}<br>

<!-- app.component.ts --><br>
import { Component, OnInit } from '@angular/core';<br>
import { DataService } from './data.service';<br>
<br>
@Component({<br>
  selector: 'app-root',<br>
  template: '<ul><li *ngFor="let user of users">{{ user.name }}</li></ul>'<br>
})<br>
export class AppComponent implements OnInit {<br>
  users: any[] = [];<br>
  constructor(private dataService: DataService) { }<br>
  ngOnInit() {<br>
    this.dataService.getUsers().subscribe(data => {<br>
      this.users = data;<br>
    });<br>
  }<br>
}<br>
      

Explanation: Pipes transform displayed values in templates. Angular has built-in pipes like Date, Currency. Custom pipes let you define your own transformations.

Example: Custom pipe to reverse a string:

<!-- reverse.pipe.ts --><br>
import { Pipe, PipeTransform } from '@angular/core';<br>
<br>
@Pipe({ name: 'reverse' })<br>
export class ReversePipe implements PipeTransform {<br>
  transform(value: string): string {<br>
    return value.split('').reverse().join('');<br>
  }<br>
}<br>

<!-- usage in template --><br>
<div>{{ 'Angular' | reverse }}</div> <!-- Output: ralugnA --><br>
      

Explanation: Angular Router enables navigation among views/components with URL paths.

Example: Basic routing setup:

<!-- app-routing.module.ts --><br>
import { NgModule } from '@angular/core';<br>
import { RouterModule, Routes } from '@angular/router';<br>
import { HomeComponent } from './home/home.component';<br>
import { AboutComponent } from './about/about.component';<br>
<br>
const routes: Routes = [<br>
  { path: '', component: HomeComponent },<br>
  { path: 'about', component: AboutComponent }<br>
];<br>
<br>
@NgModule({<br>
  imports: [RouterModule.forRoot(routes)],<br>
  exports: [RouterModule]<br>
})<br>
export class AppRoutingModule { }<br>

<!-- app.component.html --><br>
<a routerLink="">Home</a> | <a routerLink="about">About</a><br>
<router-outlet></router-outlet><br>
      

Explanation: Template-driven forms use directives in templates; Reactive forms are more powerful and use explicit form control objects in TS.

Example: Template-driven form input:

<!-- app.module.ts --><br>
import { FormsModule } from '@angular/forms';<br>
@NgModule({ imports: [FormsModule] })<br>
export class AppModule { }<br>

<!-- app.component.html --><br>
<form #myForm="ngForm"><br>
  <input name="username" ngModel required><br>
  <button type="submit">Submit</button><br>
</form><br>

<!-- app.component.ts --><br>
import { Component } from '@angular/core';<br>
@Component({ selector: 'app-root', templateUrl: './app.component.html' })<br>
export class AppComponent { }<br>
      

Explanation: Services provide reusable business logic. Angular DI injects services where needed.

Example: Simple logging service:

<!-- logger.service.ts --><br>
import { Injectable } from '@angular/core';<br>
<br>
@Injectable({ providedIn: 'root' })<br>
export class LoggerService {<br>
  log(msg: string) {<br>
    console.log('LOG:', msg);<br>
  }<br>
}<br>

<!-- app.component.ts --><br>
import { Component } from '@angular/core';<br>
import { LoggerService } from './logger.service';<br>
<br>
@Component({ selector: 'app-root', template: '<button (click)="logMessage()">Log</button>' })<br>
export class AppComponent {<br>
  constructor(private logger: LoggerService) { }<br>
  logMessage() {<br>
    this.logger.log('Button clicked!');<br>
  }<br>
}<br>
      

Explanation: Lifecycle hooks allow you to tap into component life stages like initialization and destruction.

Example: Using ngOnInit hook:

import { Component, OnInit, OnDestroy } from '@angular/core';<br>

@Component({ selector: 'app-root', template: '<div>Check console for lifecycle logs</div>' })<br>
export class AppComponent implements OnInit, OnDestroy {<br>
  ngOnInit() {<br>
    console.log('Component initialized');<br>
  }<br>
  ngOnDestroy() {<br>
    console.log('Component destroyed');<br>
  }<br>
}<br>
      

Explanation: Structural directives change the DOM layout (e.g., *ngIf, *ngFor). Attribute directives change appearance or behavior (e.g., ngClass).

Example: Using *ngIf and [ngClass]:

<div *ngIf="isVisible" [ngClass]="{'highlight': isHighlighted}">Hello Angular</div>

<!-- in component.ts -->
isVisible = true;
isHighlighted = true;
      

Explanation: HttpClient service allows you to make HTTP requests to REST APIs.

Example: Simple GET request:

<!-- app.module.ts --><br>
import { HttpClientModule } from '@angular/common/http';<br>
@NgModule({ imports: [HttpClientModule] })<br>
export class AppModule { }<br>

<!-- data.service.ts --><br>
import { Injectable } from '@angular/core';<br>
import { HttpClient } from '@angular/common/http';<br>
import { Observable } from 'rxjs';<br>
<br>
@Injectable({ providedIn: 'root' })<br>
export class DataService {<br>
  constructor(private http: HttpClient) { }<br>
  getData(): Observable<any> {<br>
    return this.http.get('https://jsonplaceholder.typicode.com/posts');<br>
  }<br>
}<br>

<!-- app.component.ts --><br>
import { Component, OnInit } from '@angular/core';<br>
import { DataService } from './data.service';<br>
<br>
@Component({ selector: 'app-root', template: '<ul><li *ngFor="let item of data">{{item.title}}</li></ul>' })<br>
export class AppComponent implements OnInit {<br>
  data: any[] = [];<br>
  constructor(private dataService: DataService) { }<br>
  ngOnInit() {<br>
    this.dataService.getData().subscribe(res => this.data = res);<br>
  }<br>
}<br>
      

Explanation: Guards protect routes from unauthorized access by controlling navigation.

Example: Simple Auth Guard:

<!-- auth.guard.ts --><br>
import { Injectable } from '@angular/core';<br>
import { CanActivate, Router } from '@angular/router';<br>
<br>
@Injectable({ providedIn: 'root' })<br>
export class AuthGuard implements CanActivate {<br>
  constructor(private router: Router) { }<br>
  canActivate(): boolean {<br>
    const loggedIn = false; // fake auth check<br>
    if (!loggedIn) {<br>
      this.router.navigate(['/login']);<br>
      return false;<br>
    }<br>
    return true;<br>
  }<br>
}<br>

<!-- app-routing.module.ts --><br>
const routes = [<br>
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }<br>
];<br>
      

Explanation: Modules group related components. Lazy loading loads feature modules only when needed to improve performance.

Example: Lazy load a feature module:

<!-- app-routing.module.ts --><br>
const routes: Routes = [<br>
  { path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }<br>
];<br>
      

Explanation: Angular animations create smooth visual effects for state changes and transitions.

Example: Simple fade animation:

import { Component } from '@angular/core';<br>
import { trigger, state, style, animate, transition } from '@angular/animations';<br>
<br>
@Component({<br>
  selector: 'app-root',<br>
  template: '<div [@fadeState]="state" (click)="toggleState()">Click me to fade</div>',<br>
  animations: [<br>
    trigger('fadeState', [<br>
      state('visible', style({ opacity: 1 })),<br>
      state('hidden', style({ opacity: 0 })),<br>
      transition('visible <=> hidden', [animate('500ms ease-in-out')])<br>
    ])<br>
  ]<br>
})<br>
export class AppComponent {<br>
  state = 'visible';<br>
  toggleState() {<br>
    this.state = this.state === 'visible' ? 'hidden' : 'visible';<br>
  }<br>
}<br>
      

Explanation: Angular i18n helps translate app text to multiple languages using built-in tools.

Example: Using i18n attribute:

<h1 i18n>Welcome to Angular</h1>

<!-- Build with localization flags, e.g.: ng build --localize --configuration=fr --output-path=dist/fr --i18n-file=src/locale/messages.fr.xlf --i18n-format=xlf --i18n-locale=fr --i18n-missing-translation=error --aot --prod --build-optimizer --source-map=false --vendor-chunk --common-chunk --delete-output-path=false --optimization --named-chunks --vendor-chunk --build-optimizer --aot --configuration=production -- --localize --configuration=fr --output-path=dist/fr --i18n-file=src/locale/messages.fr.xlf --i18n-format=xlf --i18n-locale=fr --i18n-missing-translation=error --aot --prod --build-optimizer --source-map=false --vendor-chunk --common-chunk --delete-output-path=false --optimization --named-chunks --vendor-chunk --build-optimizer --aot --configuration=production -- --localize --configuration=fr --output-path=dist/fr --i18n-file=src/locale/messages.fr.xlf --i18n-format=xlf --i18n-locale=fr --i18n-missing-translation=error --aot --prod --build-optimizer --source-map=false --vendor-chunk --common-chunk --delete-output-path=false --optimization --named-chunks --vendor-chunk --build-optimizer --aot --configuration=production -- />
      

Explanation: Template-driven forms use directives in templates; reactive forms use explicit form models in code.

Example: Template-driven form:

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

export class AppComponent {<br>
  onSubmit(value: any) {<br>
    console.log(value);<br>
  }<br>
}<br>
      

Example: Reactive form:

import { FormGroup, FormControl, Validators } from '@angular/forms';<br>
<br>
form = new FormGroup({<br>
  username: new FormControl('', Validators.required)<br>
});<br>

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

<form [formGroup]="form" (ngSubmit)="onSubmit()"><br>
  <input formControlName="username"><br>
  <button type="submit">Submit</button><br>
</form><br>
      

Explanation: Pipes transform data for display (e.g., date formatting, uppercase).

Example: Using built-in pipes:

<div>{{ today | date:'fullDate' }}</div><br>
<div>{{ name | uppercase }}</div>
      

Example: Custom pipe:

import { Pipe, PipeTransform } from '@angular/core';<br>
<br>
@Pipe({ name: 'exclaim' })<br>
export class ExclaimPipe implements PipeTransform {<br>
  transform(value: string): string {<br>
    return value + '!!!';<br>
  }<br>
}<br>

<div>{{ 'Hello' | exclaim }}</div>
      

Explanation: Structural directives change DOM layout (e.g., *ngIf). Attribute directives change element appearance or behavior.

Example: Structural directive *ngIf:

<div *ngIf="isVisible">Visible content</div>
      

Example: Attribute directive (built-in):

<button [disabled]="isDisabled">Submit</button>
      

Example: Custom attribute directive:

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';<br>
<br>
@Directive({ selector: '[appHighlight]' })<br>
export class HighlightDirective {<br>
  constructor(private el: ElementRef, private renderer: Renderer2) { }<br>
  @HostListener('mouseenter') onMouseEnter() {<br>
    this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');<br>
  }<br>
  @HostListener('mouseleave') onMouseLeave() {<br>
    this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');<br>
  }<br>
}<br>

<div appHighlight>Hover me to highlight</div>
      

Explanation: DI provides components with dependencies like services automatically.

Example: Providing a service:

import { Injectable } from '@angular/core';<br>
<br>
@Injectable({ providedIn: 'root' })<br>
export class LoggerService {<br>
  log(msg: string) { console.log(msg); }<br>
}<br>

import { Component } from '@angular/core';<br>
import { LoggerService } from './logger.service';<br>
<br>
@Component({ selector: 'app-root', template: '<button (click)="log()">Log</button>' })<br>
export class AppComponent {<br>
  constructor(private logger: LoggerService) { }<br>
  log() { this.logger.log('Button clicked'); }<br>
}<br>
      

Explanation: Lifecycle hooks let you tap into component creation, updates, and destruction.

Example: Using ngOnInit and ngOnDestroy:

import { Component, OnInit, OnDestroy } from '@angular/core';<br>
<br>
@Component({ selector: 'app-root', template: '<div>Check console</div>' })<br>
export class AppComponent implements OnInit, OnDestroy {<br>
  ngOnInit() {<br>
    console.log('Component initialized');<br>
  }<br>
  ngOnDestroy() {<br>
    console.log('Component destroyed');<br>
  }<br>
}<br>
      

Explanation: Angular Material provides UI components following Material Design principles.

Example: Using Material Button:

<!-- app.module.ts --><br>
import { MatButtonModule } from '@angular/material/button';<br>
@NgModule({ imports: [MatButtonModule] })<br>
export class AppModule { }<br>

<button mat-button>Material Button</button>
      

Explanation: Angular Universal renders Angular apps on the server for better SEO and faster first paint.

Example: Basic steps to add Angular Universal:

ng add @nguniversal/express-engine

<!-- Then run: -->
npm run build:ssr
npm run serve:ssr
      

Explanation: Routing allows navigation between views/components using URL paths.

Example: Defining routes:

import { NgModule } from '@angular/core';<br>
import { RouterModule, Routes } from '@angular/router';<br>
import { HomeComponent } from './home/home.component';<br>
import { AboutComponent } from './about/about.component';<br>

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

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

Example: Navigating in template:

<a routerLink="/">Home</a><br>
<a routerLink="/about">About</a><br>
<router-outlet></router-outlet>
      

Explanation: HttpClient service lets Angular apps communicate with backend APIs.

Example: Simple GET request:

import { HttpClient } from '@angular/common/http';<br>
import { Component } from '@angular/core';<br>

@Component({ selector: 'app-root', template: '<div>Check console</div>' })<br>
export class AppComponent {<br>
  constructor(private http: HttpClient) { }<br>
  ngOnInit() {<br>
    this.http.get('https://api.example.com/data').subscribe(data => {<br>
      console.log(data);<br>
    });<br>
  }<br>
}<br>
      

Explanation: Observables are streams of data, useful for async programming; RxJS provides operators to manipulate them.

Example: Creating and subscribing to an observable:

import { Observable } from 'rxjs';<br>

const obs = new Observable(subscriber => {<br>
  subscriber.next('Hello');<br>
  subscriber.next('World');<br>
  subscriber.complete();<br>
});<br>

obs.subscribe({<br>
  next: x => console.log(x),<br>
  complete: () => console.log('Done')<br>
});
      

Explanation: NgRx is a Redux-style state management library for Angular, using actions, reducers, and effects.

Example: Basic action and reducer:

import { createAction, createReducer, on } from '@ngrx/store';<br>

export const increment = createAction('[Counter] Increment');<br>

export const initialState = 0;<br>

export const counterReducer = createReducer( initialState,<br>
  on(increment, state => state + 1)<br>
);
      

Explanation: Angular supports multiple languages and locales through i18n.

Example: Marking text for translation:

<h1 i18n>Welcome to the app</h1>
      

Example: Using Angular CLI to extract translations:

ng extract-i18n
      

Explanation: Angular uses Jasmine and Karma for unit and integration testing.

Example: Simple component test:

import { ComponentFixture, TestBed } from '@angular/core/testing';<br>
import { AppComponent } from './app.component';<br>

describe('AppComponent', () => {<br>
  let component: AppComponent;<br>
  let fixture: ComponentFixture<AppComponent>;<br>

  beforeEach(async () => {<br>
    await TestBed.configureTestingModule({ declarations: [AppComponent] }).compileComponents();<br>
  });<br>

  beforeEach(() => {<br>
    fixture = TestBed.createComponent(AppComponent);<br>
    component = fixture.componentInstance;<br>
    fixture.detectChanges();<br>
  });<br>

  it('should create', () => {<br>
    expect(component).toBeTruthy();<br>
  });<br>
});
      

Explanation: Angular Animations provide smooth transitions and effects using the animation API.

Example: Basic fade animation:

import { trigger, state, style, animate, transition } from '@angular/animations';<br>

@Component({<br>
  selector: 'app-root',<br>
  template: '<div [@fadeInOut]>Fade me!</div>',<br>
  animations: [<br>
    trigger('fadeInOut', [<br>
      state('void', style({ opacity: 0 })),<br>
      transition(':enter, :leave', [<br>
        animate(500)<br>
      ])<br>
    ])<br>
  ]<br>
})<br>
export class AppComponent { }
      

Explanation: Angular libraries enable reusable modules/packages across apps.

Example: Creating a simple library:

ng generate library my-lib
      

Then build and publish for reuse.

Explanation: Techniques like lazy loading, OnPush change detection, and trackBy improve app speed.

Example: Lazy loading a module:

const routes: Routes = [ <br>
  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }<br>
];
      

Explanation: Angular CLI builds production-ready code with optimizations like Ahead-of-Time (AOT) compilation and minification.

Example: Building for production:

ng build --prod
      

Deploy the output in the `dist/` folder to your web server.

Explanation: Angular Universal enables server-side rendering (SSR) of Angular apps for faster initial loads and SEO improvements.

Example: Adding Angular Universal:

ng add @nguniversal/express-engine
      

This command sets up server-side rendering with Express.

Explanation: Angular Material provides UI components that follow Google’s Material Design specs, improving UI consistency and aesthetics.

Example: Installing Angular Material:

ng add @angular/material
      

Then import desired Material modules like MatButtonModule in your app module.

Explanation: Angular Animations let you create smooth transitions and effects using the Angular animations API.

Example: Basic fade animation:

import { trigger, state, style, transition, animate } from '@angular/animations';
@Component({
animations: [
trigger('fadeInOut', [
state('void', style({ opacity: 0 })),
transition(':enter, :leave', [
animate(500)
])
])
]
})
export class MyComponent {}

Explanation: Reactive Forms provide a model-driven approach to handling form inputs and validation.

Example: Creating a simple reactive form:

import { FormGroup, FormControl } from '@angular/forms';
@Component({})
export class MyComponent {
form = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
}

Explanation: Template-driven forms rely on directives in templates to create and manage forms with two-way binding.

Example: Simple template-driven form:

<form #myForm="ngForm">
<input name="username" ngModel required>
<button [disabled]="myForm.invalid">Submit</button>
</form>

Explanation: HttpClient enables Angular apps to interact with REST APIs using methods like GET, POST, PUT, DELETE.

Example: Making a GET request:

import { HttpClient } from '@angular/common/http';
@Component({})
export class MyComponent {
constructor(private http: HttpClient) {}
getData() {
this.http.get('https://api.example.com/data')
.subscribe(data => console.log(data));
}
}

Explanation: Route guards control access to routes based on conditions like authentication.

Example: Basic AuthGuard:

import { CanActivate } from '@angular/router';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
canActivate() {
return !!localStorage.getItem('token');
}
}

Explanation: Angular i18n helps translate and localize apps for multiple languages and regions.

Example: Marking text for translation:

<h1 i18n>Welcome to our app!</h1>
      

Explanation: Unit testing in Angular uses tools like Jasmine and Karma to test components and services.

Example: Simple component test:

describe('MyComponent', () => {
let component: MyComponent;
beforeEach(() => {
component = new MyComponent();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

Explanation: E2E testing simulates user interactions with Protractor or Cypress to test the whole app flow.

Example: Basic Protractor test:

describe('workspace-project App', () => {
it('should display welcome message', () => {
browser.get('/');
expect(element(by.css('h1')).getText()).toEqual('Welcome to app!');
});
});

Explanation: Angular CLI offers advanced features like custom schematics, builders, and environment configuration.

Example: Generating a component with CLI and inline styles:

ng generate component my-component --inline-style --inline-template
      

Explanation: Ivy is Angular's new rendering engine improving build times, bundle size, and debugging.

Example: Ivy is enabled by default in Angular 9+ projects.

Explanation: Lazy loading improves performance by loading modules only when needed.

Example: Defining a lazy-loaded route:

{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
      

Explanation: Change detection determines how Angular updates the DOM when data changes. Default and OnPush are common strategies.

Example: Using OnPush strategy:

@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent {}

Explanation: Custom pipes transform data in templates beyond built-in pipes.

Example: Creating a pipe to reverse a string:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}

Explanation: Dynamic components are created and inserted programmatically at runtime.

Example: Using ComponentFactoryResolver:

@ViewChild('container', { read: ViewContainerRef }) container;
constructor(private resolver: ComponentFactoryResolver) {}
const factory = this.resolver.resolveComponentFactory(MyComponent);
this.container.createComponent(factory);

Explanation: Web Workers run CPU-intensive tasks in background threads to keep UI responsive.

Example: Adding a web worker:

ng generate web-worker my-worker
      

Explanation: NgRx is a Redux-inspired state management library for Angular apps.

Example: Defining an action:

import { createAction } from '@ngrx/store';
export const loadItems = createAction('[Items] Load Items');

Explanation: Runtime localization allows switching languages dynamically without rebuilding the app.

Example: Using ngx-translate library:

import { TranslateService } from '@ngx-translate/core';
constructor(private translate: TranslateService) {
translate.use('en');
}
switchLanguage(lang: string) {
this.translate.use(lang);
}

Explanation: Angular supports PWAs for offline capability, installability, and better mobile experience.

Example: Adding PWA support:

ng add @angular/pwa
      

Explanation: ICU expressions handle complex pluralization and gender cases in translations.

Example: Using ICU in template:

{messages.length, plural, =0 {No messages} =1 {One message} other {# messages}}
      

Explanation: Template reference variables refer to DOM elements or Angular components within a template.

Example: Using a template variable to access input value:

<input #myInput type="text">
<button (click)="logValue(myInput.value)">Log Input</button>

Explanation: ElementRef accesses DOM elements; Renderer2 safely manipulates DOM to maintain platform agnosticism.

Example: Changing background color:

constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.renderer.setStyle(this.el.nativeElement, 'background-color', 'yellow');
}

Explanation: Zones detect async operations and trigger change detection. NgZone allows manual control over this behavior.

Example: Running code outside Angular zone:

constructor(private ngZone: NgZone) {}
this.ngZone.runOutsideAngular(() => {
setTimeout(() => {
console.log('Outside Angular zone');
}, 1000);
});

Explanation: DomSanitizer helps prevent Cross-Site Scripting (XSS) by sanitizing untrusted values.

Example: Bypass security to trust a URL:

constructor(private sanitizer: DomSanitizer) {}
getTrustedUrl(url: string) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

Explanation: Angular's i18n support allows you to translate your app into different languages using built-in tools.

Example: Marking text for translation:

<h1 i18n>Welcome to our site</h1>
      

Explanation: Custom pipes let you transform data in templates beyond the built-in pipes.

Example: Creating a pipe to reverse a string:

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

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

Explanation: Angular animations allow smooth transitions and state changes with the animation DSL.

Example: Simple fade-in animation:

import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
selector: 'app-fade',
templateUrl: './fade.component.html',
animations: [
trigger('fadeIn', [
state('void', style({ opacity: 0 })),
transition(':enter', [animate('500ms ease-in')])
])
]
})
export class FadeComponent {}

Explanation: Custom builders extend Angular CLI to customize build and deploy processes.

Example: Define a custom builder in angular.json and implement it in code (conceptual overview).

Explanation: Jasmine is used for unit testing Angular components; Karma runs tests in browsers.

Example: Basic Jasmine test:

describe('MyComponent', () => {
it('should create', () => {
const comp = new MyComponent();
expect(comp).toBeTruthy();
});
});

Explanation: Angular provides Default and OnPush change detection to optimize component updates.

Example: Setting OnPush strategy:

@Component({
selector: 'app-onpush',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<p>OnPush Example</p>'
})
export class OnPushComponent {}

Explanation: HTTP interceptors allow you to modify requests and responses globally.

Example: Adding an Authorization header:

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

Explanation: Lazy loading loads modules on demand, improving startup time and performance.

Example: Route configuration with lazy loading:

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

Explanation: FormArray is used to manage an array of form controls, often for dynamic forms.

Example: Creating a dynamic list of inputs:

this.form = this.fb.group({
aliases: this.fb.array([
this.fb.control('')
])
});

get aliases() {
return this.form.get('aliases') as FormArray;
}

Explanation: Guards protect routes by controlling access based on conditions.

Example: CanActivate guard:

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

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

Explanation: Content projection lets you insert external content into a component using <ng-content>.

Example: Using ng-content:

<div class="card">
<ng-content></ng-content>
</div>

Explanation: Renderer2 is Angular's recommended way to safely manipulate the DOM.

Example: Adding a CSS class:

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

ngOnInit() {
this.renderer.addClass(this.el.nativeElement, 'my-class');
}

Explanation: Angular Universal enables server-side rendering to improve performance and SEO.

Example: Basic setup involves running Angular on the server with Node.js (conceptual).

Explanation: Angular Service Workers enable Progressive Web App features like offline support and caching.

Example: Add service worker support with CLI command:

ng add @angular/pwa
      

Explanation: Dynamic components are created and inserted at runtime.

Example: Using ComponentFactoryResolver:

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

const factory = this.resolver.resolveComponentFactory(MyComponent);
this.container.clear();
this.container.createComponent(factory);

Explanation: Environment files manage app configurations per environment (dev, prod).

Example: Accessing environment variables:

import { environment } from '../environments/environment';

console.log(environment.apiUrl);

Explanation: Router events allow you to listen to navigation lifecycle events.

Example: Subscribe to NavigationStart:

this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
console.log('Navigation started');
}
});

Explanation: Angular Universal enables server-side rendering, improving SEO and performance.

Example: Setting up Angular Universal involves running:

ng add @nguniversal/express-engine
      

Explanation: Angular Service Workers add offline caching and enable Progressive Web App features.

Example: Add PWA support:

ng add @angular/pwa
      

Explanation: Ivy is Angular's next-generation rendering engine, providing faster compilation and smaller bundles.

Example: Ivy is enabled by default in Angular 9+; no extra setup needed.

Explanation: ElementRef gives direct access to DOM elements; ViewChild gets component or element references.

Example: Using ViewChild to access a button:

@ViewChild('myButton') button: ElementRef;

ngAfterViewInit() {
this.button.nativeElement.style.backgroundColor = 'blue';
}

Explanation: Angular injectors form a hierarchy controlling provider instances and scope.

Example: Services provided in root are singleton; providers in components create new instances.

Explanation: ngDoCheck allows custom change detection beyond default mechanisms.

Example: Implementing ngDoCheck:

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

Explanation: trackBy improves performance by tracking items by unique identifier.

Example: Using trackBy in *ngFor:

<div *ngFor="let item of items; trackBy: trackById">{{ item.name }}</div>

trackById(index: number, item: any): number {
return item.id;
}

Explanation: RendererFactory2 creates Renderer2 instances and is used in advanced scenarios.

Example: Injecting RendererFactory2:

constructor(private rendererFactory: RendererFactory2) {
this.renderer = rendererFactory.createRenderer(null, null);
}

Explanation: Resolvers pre-fetch data before route activation, ensuring data is ready.

Example: Defining a resolver:

@Injectable({ providedIn: 'root' })
export class DataResolver implements Resolve<Data> {
constructor(private service: DataService) {}

resolve(route: ActivatedRouteSnapshot) {
return this.service.getData(route.params['id']);
}
}

Explanation: Load and render components dynamically at runtime.

Example: Using ComponentFactoryResolver:

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

loadComponent() {
const factory = this.resolver.resolveComponentFactory(MyComponent);
this.container.clear();
this.container.createComponent(factory);
}

Explanation: FormArray is a way to manage an array of FormControls or FormGroups.

Example: Creating a FormArray:

this.form = this.fb.group({
phones: this.fb.array([
this.fb.control('')
])
});

get phones() {
return this.form.get('phones') as FormArray;
}

Explanation: Template reference variables give a way to refer to elements in the template.

Example: Defining a template reference variable:

<input #myInput type="text">
<button (click)="myInput.value = ''">Clear</button>

Explanation: Angular provides tools for internationalization (i18n) and localization.

Example: Use i18n attribute:

<h1 i18n>Hello World</h1>
      

Explanation: Content projection allows you to insert content inside a component from the outside.

Example: Using ng-content:

<my-card>
<h2>Title</h2>
<p>This is content inside the card.</p>
</my-card>

Explanation: Angular Animations provide powerful animation capabilities via the @angular/animations package.

Example: Basic fade animation:

import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
animations: [
trigger('fadeInOut', [
state('void', style({ opacity: 0 })),
transition(':enter, :leave', [
animate(500)
])
])
]
})
export class MyComponent {}

Explanation: HTTP interceptors can modify requests or responses globally.

Example: Creating an interceptor:

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

Explanation: Custom pipes transform data in templates.

Example: Creating a custom pipe:

@Pipe({ name: 'exclaim' })
export class ExclaimPipe implements PipeTransform {
transform(value: string): string {
return value + '!!!';
}
}

Explanation: NgZone lets you run code inside or outside Angular's change detection.

Example: Using NgZone:

constructor(private ngZone: NgZone) {}

this.ngZone.runOutsideAngular(() => {
// code that should not trigger change detection
});

Explanation: Dynamically apply styles and classes in templates.

Example:

<div [ngStyle]="{ color: isRed ? 'red' : 'blue' }">Styled Text</div>
<div [ngClass]="{ active: isActive, disabled: isDisabled }">Class Bound</div>

Explanation: Load feature modules only when needed to improve performance.

Example: In routing:

{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }
      

Explanation: View encapsulation controls CSS scope: Emulated, None, ShadowDom.

Example:

@Component({
encapsulation: ViewEncapsulation.Emulated
})

Explanation: Jasmine and Karma are used for unit testing Angular applications.

Example: Basic test spec:

describe('MyComponent', () => {
it('should create', () => {
expect(component).toBeTruthy();
});
});

Angular Universal is a technology for server-side rendering (SSR) of Angular applications. It renders Angular apps on the server, which improves performance, especially for the first load, enhances SEO by serving fully rendered pages to search engines, and provides a better user experience on slow networks or devices.

Lazy loading delays the loading of Angular modules until they are needed, reducing the initial load time. It is implemented by using the loadChildren property in the route configuration with dynamic imports.

const routes: Routes = [<br>
  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }<br>
];<br>
      

Angular decorators are functions that add metadata to classes, properties, methods, or parameters to inform Angular how to process them. Common decorators include @Component for components, @NgModule for modules, and @Injectable for services.

@Component({<br>
  selector: 'app-example',<br>
  templateUrl: './example.component.html'<br>
})<br>
export class ExampleComponent { }<br>
      

Angular's change detection system tracks changes to data-bound properties and updates the DOM accordingly. It runs after asynchronous events like user input, timers, or HTTP requests, checking component bindings and updating the view efficiently.

Pipes transform displayed data in templates. Angular provides built-in pipes like date and uppercase, and you can create custom pipes by implementing the PipeTransform interface.

import { Pipe, PipeTransform } from '@angular/core';<br>
@Pipe({ name: 'exclaim' })<br>
export class ExclaimPipe implements PipeTransform {<br>
  transform(value: string): string {<br>
    return value + '!!!';<br>
  }<br>
}<br>
      

The Angular CLI is a command-line interface tool that automates development tasks like creating components, services, and running tests. To generate a component, you run:

ng generate component component-name<br>
<br>
ng g c component-name<br>
      

Angular supports two types of forms: template-driven and reactive forms. Template-driven forms rely on directives in the template, suitable for simple forms. Reactive forms use explicit, programmatic form control objects for more complex scenarios.

Observables are used in Angular for asynchronous operations, such as handling HTTP requests or user events. They provide a powerful way to manage streams of data and support operators for transformation and filtering.

Angular components communicate via Input and Output decorators, services with shared state, or event emitters. Input passes data from parent to child, Output sends events from child to parent.

@Input() childData: string;<br>
@Output() notify = new EventEmitter();<br>
      

Directives are classes that add behavior to elements in Angular templates. Types include components (with templates), attribute directives (change appearance/behavior), and structural directives (change DOM layout like *ngIf, *ngFor).

Performance can be improved by using OnPush change detection strategy, lazy loading modules, trackBy in *ngFor, Ahead-of-Time (AOT) compilation, and minimizing bindings and watchers.