Knowledge / Computer Applications / TypeScript and Angular

TypeScript and Angular

Computer Applications (MCA) · Enterprise and web development · free study notes for exams, placements and interviews

In short

TypeScript is a statically typed superset of JavaScript: it adds types, interfaces, generics, enums and decorators, and compiles ("transpiles") down to plain JavaScript that any browser or Node.js runtime can execute. Angular is Google's full, opinionated front-end framework written in TypeScript — it ships its own component model, dependency injection, router, HTTP client, forms engine and build toolchain, so a team does not assemble these from third-party libraries. The pair matters because large enterprise applications need compile-time safety and a consistent structure across many developers, which is exactly why Indian IT services and product firms (TCS, Infosys, Wipro, Accenture, Cognizant, Capgemini, HCLTech, Zoho, Freshworks, banks and insurers) list "Angular with TypeScript" on most full-stack and UI job descriptions. In university exams (MCA web technology / enterprise application development papers) it appears as component architecture, data binding types, directives, services and DI, routing and forms; in placement rounds it appears as live coding plus questions on strict typing, observables, change detection and lifecycle order. GATE DA/CS does not examine Angular, so for MCA the weight is university practicals, project work and interviews.

Explained

TypeScript language essentials

Angular architecture and building blocks

Change detection, RxJS and signals

HTTP, routing, forms

Tooling, build, testing and quality

Key points

Examples

Example 1 — typed model, generic service and DI.

export interface Student { roll: number; name: string; cgpa: number; }

@Injectable({ providedIn: 'root' })
export class ApiService {
  constructor(private http: HttpClient) {}
  list<T>(url: string): Observable<T[]> { return this.http.get<T[]>(url); }
}

@Component({
  selector: 'app-toppers',
  standalone: true,
  imports: [DecimalPipe],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @for (s of toppers(); track s.roll) {
      <p>{ s.name } — CGPA <span [title]="s.roll.toString()">{ s.cgpa | number:'1.2-2' }</span></p>
    } @empty { <p>No records</p> }`
})
export class ToppersComponent implements OnInit {
  toppers = signal<Student[]>([]);
  private api = inject(ApiService);
  private destroyRef = inject(DestroyRef);
  ngOnInit(): void {
    this.api.list<Student>('/api/students')
      .pipe(map(rows => rows.filter(r => r.cgpa >= 8.5)), takeUntilDestroyed(this.destroyRef))
      .subscribe(rows => this.toppers.set(rows));
  }
}

In a real template the two placeholder spans shown as single braces are written with Angular's double-brace interpolation; track s.roll is mandatory in @for and lets Angular reuse DOM nodes instead of rebuilding the list.

Example 2 — strict null checking catching a bug.

function fee(f?: number) { return f.toFixed(2); }   // error under strict: 'f' is possibly undefined
function feeOk(f?: number) { return (f ?? 0).toFixed(2); }  // compiles
console.log(feeOk(45000), feeOk());   // "45000.00" and "0.00"

Without strictNullChecks the first version compiles and throws TypeError in the browser when the field is missing from the API response.

Example 3 — type-ahead search with the right operator. A college-fee portal search box fires on every keystroke. With mergeMap, typing "ANNA" (4 keystrokes) issues 4 requests and the slowest response wins, so the box can show results for "ANN". The fix:

this.search.valueChanges.pipe(
  debounceTime(300), distinctUntilChanged(),
  switchMap(q => this.api.list<Student>(`/api/search?q=${q}`)),
  catchError(() => of([]))
).subscribe(r => this.rows.set(r));

debounceTime(300) reduces 4 keystrokes typed within 300 ms to 1 request; switchMap cancels any in-flight request, so at most one response reaches the view and it is always the latest query's.

Example 4 — reactive form with a cross-field validator.

const form = this.fb.group({
  pan: ['', [Validators.required, Validators.pattern(/^[A-Z]{5}[0-9]{4}[A-Z]$/)]],
  password: ['', [Validators.required, Validators.minLength(8)]],
  confirm: ['']
}, { validators: g => g.value.password === g.value.confirm ? null : { mismatch: true } });

"ABCDE1234F" passes the PAN pattern (5 letters, 4 digits, 1 letter); "ABCD1234F" fails. Note the pattern checks *format only* — statutory validity is verified server-side against the issuing authority, never in the browser.

Example 5 — bundle size and lazy loading. A production build reports: main 420 KB, admin feature 300 KB, reports feature 280 KB (uncompressed, after AOT and minification), total 1,000 KB. Eager: every user downloads 1,000 KB. After moving admin and reports to loadComponent routes, a normal student downloads 420 KB — a 58% reduction in initial payload; an admin pays the extra 300 KB only on navigating to that route. A CLI budget of maximumError: 500kb on the initial bundle fails the build if the split is later undone.

AspectTemplate-driven formsReactive forms
Source of truthTemplate (ngModel)TypeScript class (FormGroup)
ModuleFormsModuleReactiveFormsModule
Data flowAsynchronousSynchronous
TypingWeakStrictly typed
Dynamic controlsHardFormArray, easy
Unit testingNeeds rendered DOMTest the model directly
Best forSmall/simple formsEnterprise, validated, dynamic forms
AspectObservable (RxJS)Promise
Values0..n over timeExactly 1
ExecutionLazy, on subscribeEager, on creation
Cancellationunsubscribe()Not cancellable
Operatorsmap, filter, retry, debounce....then chaining only
Angular useHttpClient, forms, router eventsInterop via from(promise)

Where it is used

Interview questions

Common mistakes

Related topics

Front-end frameworks: React basics · Back-end development with Node.js · REST APIs · Authentication and authorisation: sessions, OAuth and JWT · Spring Boot and microservices development · API design: GraphQL, gRPC and OpenAPI

Open in the Knowledge reader →Find jobs →