Questions 1–20 of 195 · 0 of 20 on this page marked learned
1.angular-0001Easyfresher
How does a modern Angular application start up, and what are the main building blocks of its structure?
A modern Angular app starts when main.ts calls bootstrapApplication with a root standalone component and an ApplicationConfig that lists the app-wide providers. The main building blocks are components, templates, services, and the router, all wired together by dependency injection.
Full answer
Angular is a framework for building single-page web apps in TypeScript. The browser loads one HTML page, and Angular builds and updates the visible screen from components.
The start-up path is short. The file main.ts calls bootstrapApplication(App, appConfig). The first argument is the root component. It is placed wherever its selector (here app-root) appears in index.html. The second argument is an ApplicationConfig object. Its providers array holds app-wide settings such as the router, the HTTP client, and the change detection strategy.
Think of a school. The root component is the school building. Each class room is a component inside it. A service is a shared office, such as the exam office, that many rooms ask for help. Dependency injection is the system that hands each room the office it needs, so no room builds its own.
The main building blocks are:
Components: a TypeScript class plus an HTML template, which together describe one piece of the screen.
Services: plain classes that hold shared logic or data, such as calling an API.
Routing: maps URLs to components.
Dependency injection: creates services and gives them to whoever asks.
Before Angular 14 every app needed an AppModule (an NgModule) for this. Since Angular 17 the CLI generates standalone apps by default, and this is the modern approach. NgModules still exist in older code bases.
typescript
// file: main.ts
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app.config';
@Component({
selector: 'app-root',
template: `<h1>{{ title }}</h1>`,
})
export class App {
title = 'Class 10 marks board';
}
bootstrapApplication(App, appConfig).catch((err) => console.error(err));
// file: app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true })],
};
Checked with Angular 20.3 and TypeScript 5.8 (type-checked with the Angular compiler in strict template mode). Place the `<app-root></app-root>` tag in index.html and run it with `ng serve`. The Angular 20 CLI names the generated root class `App` in `app.ts`, and older projects use `AppComponent` in `app.component.ts`. Both styles are valid.
Key points
`bootstrapApplication(RootComponent, config)` is the modern entry point; `platformBrowserDynamic().bootstrapModule(AppModule)` is the legacy one.
`ApplicationConfig.providers` holds app-wide providers such as `provideRouter` and `provideHttpClient`.
Components render the UI, services hold shared logic, and the injector connects them.
Standalone components are the default from Angular 19 onward, so no `AppModule` is needed.
Common mistakes
Describing Angular as a library. It is a full framework with routing, forms, HTTP, and testing tools included.
Saying every app needs an `AppModule`. That is true only for older NgModule-based projects.
Forgetting that the selector in the root component must match a tag in `index.html`, otherwise nothing renders.
Follow-ups
What does `provideZoneChangeDetection({ eventCoalescing: true })` change?
Where would you register an HTTP interceptor in this structure?
How is this different from bootstrapping with an NgModule?
Tips
Name the entry call (`bootstrapApplication`) and the config object. Many candidates only say "main.ts starts the app".
Mention that you know both the standalone and the NgModule start-up, and say which one new projects use.
Draw a quick box diagram on the whiteboard: root component, child components, services on the side.
Evaluation rubric
Names bootstrapApplication and ApplicationConfig.
Explains the role of components, services, and DI in one or two sentences each.
Knows NgModules are legacy but still seen in old projects.
2.angular-0002Easyfresher
What is an Angular component, and what do the main properties of the @Component decorator do?
A component is a TypeScript class marked with @Component that owns a template, optional styles, and the data and methods the template uses. The decorator tells Angular its selector, the template, the styles, and which other components, directives, and pipes the template may use.
Full answer
A component is the basic piece of an Angular screen. It has three parts: a class (the data and behaviour), a template (the HTML), and styles (the CSS). The @Component decorator joins them and tells Angular how to use the class.
The properties you meet most often:
selector: the custom HTML tag name, for example app-score-card. Using that tag in another template creates the component there.
template or templateUrl: the HTML. Inline template suits short markup. templateUrl points to a separate file.
styles or styleUrl: the CSS. By default styles are scoped to this component only, because Angular adds a unique attribute to its elements (view encapsulation, emulated mode).
imports: the standalone components, directives, and pipes that this template is allowed to use. If the template uses <app-badge> and it is not in imports, the compiler reports an error.
changeDetection: Default or OnPush, which decides how often Angular re-checks this component.
Each time you write <app-score-card> Angular creates a new instance of the class, so two score cards on one page have separate data.
Style scoping is a common surprise. A rule such as h2 { color: red } inside a component does not touch an h2 in another component.
Angular 20.3. The score card can be used as `<app-score-card subject="Maths" [marks]="92" />` in a parent template if the parent imports it.
Key points
A component is a class, a template, and styles tied together by `@Component`.
`selector` is the tag name, and `imports` lists what the template can use.
Styles are scoped to the component by default (emulated view encapsulation).
Each use of the tag creates a separate instance.
Common mistakes
Using a child component in a template without adding it to `imports`. The build fails with an unknown element error.
Expecting a global style written inside a component to affect other components.
Putting a lot of logic and HTTP calls in the component class. That belongs in a service.
Follow-ups
What is the difference between `template` and `templateUrl`?
How would you style an element inside a child component from the parent?
What does `ViewEncapsulation.None` do?
Tips
Give one sentence on each property you mention. A bare list sounds memorised.
Say that `standalone: true` is the default in Angular 19 and later, so you do not write it.
If asked about styles, mention emulated encapsulation and that it is not a real shadow DOM.
Evaluation rubric
Names selector, template, styles, and imports correctly.
Understands style scoping.
Mentions that logic belongs in services.
3.angular-0003Easyfresher
What are the four kinds of data binding in Angular templates, and how is each written?
Interpolation prints a value as text, property binding sets a DOM property with [prop], event binding listens with (event), and two-way binding combines both with [(prop)]. Data flows from class to template, from template to class, or both ways.
Full answer
Binding connects the class (data) to the template (screen). There are four forms.
Interpolation, {{ expression }}: prints the result of an expression as text. Example: {{ student }}.
Property binding, [property]="expression": sets a property of a DOM element or an input of a component. Example: [disabled]="marks >= 100". The value is any expression, not only a string.
Event binding, (event)="statement": runs code when an event happens, such as (click)="addMarks()". The built-in $event gives the event object.
Two-way binding, [(property)]="field": the "banana in a box" syntax. It is short for [property]="field" plus (propertyChange)="field = $event". With forms it is written [(ngModel)] and needs FormsModule.
There are also special property-like forms. [attr.aria-label] sets an HTML attribute, [class.passed]="isPassed" toggles one CSS class, and [style.width.px]="width" sets one style.
Property binding sets properties, not attributes. For most elements the two look the same, but they differ for things like value on an input, and for ARIA attributes that have no matching property (use [attr.*] for them).
In current Angular, a component can offer its own two-way binding with model(). A parent then writes [(rating)]="value" on the child.
Rules that help in practice:
Expressions should be simple and cheap, because Angular evaluates them on every check. Put heavy work in a computed or a method that is called once.
Interpolation never inserts HTML. If a student name contains <b>, the browser shows the characters, not bold text. This is a basic protection against script injection.
Expressions cannot contain assignments (except in event statements), new, or ; chains. Use the class for logic.
Use the safe navigation operator for values that may be missing: {{ student?.name }}. With signals, read student()?.name.
In an event binding, the statement is a small piece of code, so call one method. (input)="name.set($any($event.target).value)" works, but a typed handler method is easier to test.
Example for a marks page: <input [value]="marks()" (input)="update($event)" /> shows the value from the class and sends each keystroke back, which is exactly what [(ngModel)] writes in one short form.
Two-way binding is property binding plus event binding.
Use `[attr.name]` for attributes with no DOM property, `[class.x]` and `[style.x]` for single class and style.
`[(ngModel)]` needs `FormsModule` in the component `imports`.
Common mistakes
Writing `disabled="isLocked"` and expecting a binding. Without brackets it is the plain string "isLocked", which is truthy.
Importing nothing for `ngModel` and getting the error "Can't bind to 'ngModel' since it isn't a known property of 'input'".
Calling a heavy function inside interpolation. It runs on every change detection pass.
Follow-ups
What is the difference between a DOM property and an HTML attribute?
How does `[(ngModel)]` expand into property and event binding?
How can your own component support `[(value)]`?
Tips
Show you know two-way binding is sugar over two one-way bindings. This is the most common follow-up.
Write the four forms from memory on the whiteboard, with one tiny example each.
Mention `[attr.aria-label]` to show you think about accessibility.
Evaluation rubric
Writes all four syntaxes correctly.
Explains the expansion of two-way binding.
Knows the attribute vs property difference.
4.angular-0004Easyfresher
What are standalone components, and how do they differ from the older NgModule approach?
A standalone component declares its own dependencies in its imports array and needs no NgModule. NgModules are the older way, where components were declared in a module that listed what they could use. Standalone is the default for new code from Angular 19.
Full answer
Before Angular 14, every component had to belong to exactly one NgModule. The module's declarations listed the component, its imports listed other modules whose pieces the template could use, and its exports listed what other modules could see. Beginners found this confusing, because the template's dependencies were declared far from the template.
A standalone component skips the module. It lists what its template needs directly in its own imports array: other standalone components, directives, pipes, or even whole NgModules (for example FormsModule). Nothing else is needed.
The important differences:
Dependencies live next to the template, so the file is easier to read and to move.
Bundlers can remove unused code more easily, since there is no large shared module.
App-wide services are registered with provide... functions in ApplicationConfig, not in a root module.
Lazy loading works per component with loadComponent.
Version notes: standalone arrived as a developer preview in Angular 14 and was stable in 15. From Angular 19, standalone: true is the default, so you only write standalone: false for a component that must be declared in a module. NgModules are not removed, and old libraries still ship them. A standalone component can import an NgModule, and an NgModule can import a standalone component, so migration can be done step by step.
typescript
import { Component, NgModule } from '@angular/core';
// Legacy style: a component declared inside an NgModule.
@Component({
selector: 'app-old-badge',
standalone: false,
template: `<span>Legacy badge</span>`,
})
export class OldBadgeComponent {}
@NgModule({
declarations: [OldBadgeComponent],
exports: [OldBadgeComponent],
})
export class OldBadgeModule {}
// Modern style: a standalone component that lists its own dependencies.
@Component({
selector: 'app-page',
imports: [OldBadgeModule],
template: `
<h1>Report card</h1>
<app-old-badge />
`,
})
export class PageComponent {}
Angular 20.3. The module part of this file is the legacy style, kept to show interoperability. A component in an NgModule must set `standalone: false` in Angular 19 and later.
Key points
Standalone: `imports` is on the component. NgModule: components go in `declarations` and the module lists `imports`.
From Angular 19, components are standalone by default; the flag is only written to opt out.
Standalone components can import NgModules, so both styles work together.
NgModules are legacy for new code but common in older projects.
Common mistakes
Putting a standalone component in `declarations`. It must go in `imports`.
Writing `standalone: true` in every component of an Angular 19 or 20 project. It is allowed but unnecessary.
Thinking NgModules are deleted from Angular. They are still supported.
Follow-ups
How would you migrate a large NgModule app step by step?
What does `importProvidersFrom` do in an application config?
How does the Angular CLI help with migration?
Tips
Give the reason for the change (simpler mental model, less boilerplate), not only the syntax.
Say clearly which style you would use in a new project and that you can still read NgModule code.
If you have maintained a legacy app, mention the `ng generate @angular/core:standalone` migration schematic.
Evaluation rubric
Explains where dependencies are declared in each style.
Knows the version history roughly (14, 15, 19).
Mentions interoperability.
5.angular-0005Easyfresher
What are signals in Angular, and how do signal(), computed(), set() and update() work?
A signal is a wrapper around a value that tells Angular when the value changes. signal() creates a writable one, computed() derives a read-only value that updates automatically, and set() and update() change the stored value. You read a signal by calling it like a function.
Full answer
A signal holds a value and keeps a list of who is reading it. When the value changes, the readers are told. Angular uses this to update only the parts of the screen that depend on that value.
const marks = signal(80) creates a writable signal. Read it with marks().
marks.set(90) replaces the value.
marks.update(m => m + 5) computes the new value from the old one.
const grade = computed(() => marks() >= 75 ? 'A' : 'B') creates a read-only signal that is calculated from other signals.
computed is lazy and cached. It does not run until someone reads it, and it does not run again until a signal it used has changed. If nothing changed, reading it returns the stored result. This is like a canteen bill that is only re-added when you add a new item.
Signals must be read by calling them. In a template write {{ marks() }}, not {{ marks }}.
Updates must not mutate objects in place. If a signal holds an array, list.update(l => [...l, x]) notifies readers, but list().push(x) does not, because the signal sees the same array reference.
Signals are stable in Angular 20 for signal, computed, effect, linkedSignal, and signal-based inputs and queries.
typescript
import { computed, signal } from '@angular/core';
const marks = signal(80);
const grade = computed(() => (marks() >= 75 ? 'A' : 'B'));
marks.update((m) => m + 5);
console.log(grade(), marks());
marks.set(60);
console.log(grade(), marks());
const list = signal<number[]>([60]);
list.update((l) => [...l, 65]);
console.log(list().length > 1 ? 'A' : 'B', list()[1]);
Run with Node 22.18 or newer (type stripping is on by default) after `npm i @angular/core`, using a package.json with `"type": "module"`, then `node main.ts`. Signals work outside components. Output: `A 85`, then `B 60`, then `A 65`.
Key points
Read with `s()`, write with `s.set(v)` or `s.update(fn)`.
`computed` is lazy, cached, and read-only.
Signals compare values with `Object.is`, so a mutated object or array does not trigger updates.
Templates must call the signal: `{{ count() }}`.
Common mistakes
Forgetting the parentheses in the template and printing the function instead of the value.
Mutating an array held in a signal with `push` and expecting the screen to update.
Trying to call `set` on a `computed`. It is read-only and does not have `set`.
Follow-ups
How is a signal different from an RxJS BehaviorSubject?
When does a computed recalculate?
What happens if you call `set` with the same primitive value?
Tips
Use a simple example such as marks and grade. Short code you can write live is worth more than theory.
Say that `computed` should have no side effects.
If asked about RxJS, say signals suit synchronous state and RxJS suits event streams over time.
Evaluation rubric
Calls signals as functions and uses set and update correctly.
Describes computed as lazy and cached.
Knows about immutable updates.
6.angular-0006Easyfresher
How do you pass data into and out of a component with input(), output() and model()?
input() declares a signal-based input that the parent sets, output() declares an event emitter the child fires, and model() declares a value that works as a two-way binding. They replace the @Input and @Output decorators in new code.
Full answer
A parent talks to its child through inputs. The child talks back through outputs.
input<T>() creates a read-only signal that is filled by the parent. Variants:
input(5) has a default value.
input.required<number>() has no default, and the parent must set it. The compiler checks this at build time.
input(false, { transform: booleanAttribute }) converts the incoming value, so <app-x disabled /> works.
input(1, { alias: 'max' }) changes the public name.
output<T>() creates an emitter. The child calls .emit(value) and the parent listens with (name)="handler($event)".
model<T>() creates a writable signal that also works as an input and an output at the same time. The parent can write [(rating)]="stars", and the child can call rating.set(4) to push the new value up.
Because inputs are signals, you use computed for derived values and do not need ngOnChanges. Reading this.max() inside a computed or template updates automatically.
Legacy: @Input() and @Output() change = new EventEmitter<T>() still work and are common in older code. Signal inputs were introduced in 17.1 and became stable in Angular 19.
Details that interviewers often ask about:
Input signals are read-only inside the child. To keep a local editable copy that resets when the parent value changes, use linkedSignal(() => this.value()).
A required input cannot be read in the constructor, because the parent has not set it yet. The compiler reports this. Read it in a computed, an effect, or ngOnInit.
model() can be required too (model.required<number>()). If the parent uses only [rating]="x", it behaves as a plain input. If it uses [(rating)], writes go back up.
Output names should describe what happened (saved, selectionChange) and should not start with on, because the parent writes (saved)="onSaved($event)".
output() is not an observable, but you can bridge it with outputFromObservable() and outputToObservable() from @angular/core/rxjs-interop.
When you create a component in code, set inputs with componentRef.setInput('name', value), so change detection and signals see the change.
For a simple case, a student-card component takes name and marks as inputs and fires selected when the user clicks it. The parent owns the data, the child reports events. This one-way data flow keeps bugs easy to find.
Angular 20.3. In the parent write `<app-rating [max]="5" [(value)]="stars" (rated)="log($event)" />`.
Key points
`input()` and `input.required()` give signals that cannot be written by the child.
`output()` replaces `@Output` plus `EventEmitter` for new code.
`model()` gives two-way binding with `[(name)]`.
`transform` and `alias` are options on `input`.
Common mistakes
Reading an input in the constructor. The value is not set yet. Use a `computed`, an `effect`, or `ngOnInit`.
Trying to call `set` on an `input()`. Only `model()` is writable by the child.
Forgetting the parentheses when reading, so the template shows a function.
Follow-ups
Why does `input.required` have no default value?
How would you react to an input change without `ngOnChanges`?
When would you still use `@Input` today?
Tips
Show all three functions in one tiny rating component. Interviewers like a complete round trip.
Mention that required inputs are checked by the compiler, not only at runtime.
Name the legacy decorators and say they are not removed.
Evaluation rubric
Uses input, output, and model correctly.
Knows how required, transform, and alias work.
Can connect inputs to computed values.
7.angular-0007Easyfresher
How do the built-in @if, @for and @switch blocks work, and how do they compare with *ngIf and *ngFor?
@if, @for and @switch are template syntax built into the compiler since Angular 17. They replace the *ngIf, *ngFor and *ngSwitch directives, need no imports, support @else and @empty, and make track mandatory in @for.
Full answer
Angular 17 added a new block syntax for conditions and loops. It is part of the template compiler, so you import nothing.
@if (condition) { ... } @else if (other) { ... } @else { ... } shows content conditionally. You can keep the value with @if (user(); as u) { {{ u.name }} }.
@for (item of items; track item.id) { ... } @empty { ... } repeats content. Inside you get $index, $first, $last, $even, $odd, and $count. @empty renders when the list is empty.
The older directives are *ngIf, *ngFor, and *ngSwitch, from CommonModule. They still work, but they are deprecated as of Angular 20 and the team plans to remove them in a later major version. Use ng generate @angular/core:control-flow to migrate a project automatically.
Why was it changed? The block syntax reads like normal code, needs no ng-template for else branches, has better type narrowing, and the @for loop is faster than *ngFor. Benchmarks published by the Angular team showed a noticeable speed gain for large lists because the diffing algorithm was reworked.
A related feature is @let name = expression; (stable in Angular 19) which declares a read-only variable inside a template.
Angular 20.3, type-checked in strict template mode. Replace the hard-coded list with real data in a project.
Key points
`@if`, `@for`, `@switch` need no imports and are built into the compiler.
`@for` requires `track`, and has `@empty` plus `$index`-style variables.
`*ngIf` and `*ngFor` are legacy and deprecated from Angular 20.
A migration schematic converts old templates automatically.
Common mistakes
Writing `@for (item of items)` without `track`. This is a compile error.
Carrying over the old `*ngIf="x; else tpl"` pattern with an `ng-template`. In the new syntax the else branch is written as `@else { ... }` directly after the `@if` block.
Mixing `*ngIf` and `@if` in the same template without realising the old one still needs `NgIf` in `imports`.
Follow-ups
What does `track` do, and what would you track in a list from an API?
How does `@if (x(); as value)` help with type narrowing?
What is `@let` and when would you use it?
Tips
Say that you know the old syntax well because many projects still use it, then show the new syntax.
Mention the migration command. It signals real project experience.
If asked for the reason, talk about readability and performance, not only "it is new".
Evaluation rubric
Writes @if with @else, @for with track and @empty, and @switch correctly.
Labels *ngIf and *ngFor as legacy.
Knows track is required.
8.angular-0008Easyfresher
Why is the track expression required in @for, and what should you track?
track tells Angular how to match old list items to new ones, so it can reuse existing DOM nodes when the list changes instead of destroying and rebuilding them. Track a unique, stable identity such as an id. Track $index only for lists that never reorder.
Full answer
When the array behind a @for changes, Angular must decide which DOM nodes to keep, move, add, or remove. The track expression produces a key for each item. Items with the same key between two renders are treated as the same item, so Angular reuses its DOM and updates only what changed.
Without a stable key, Angular would have to rebuild the whole list when you receive fresh objects from an API, even if the data is the same. That loses input focus, scroll position inside rows, running animations, and costs time.
What to track:
A unique id from the data, for example track student.id. This is the best choice.
track $index is fine for a static list that never reorders, or for a simple list of primitives where the position is the identity.
track item (the object itself) works only if the same object references stay in the array. After an HTTP refresh, the new objects have new references, so everything rebuilds.
The old *ngFor had an optional trackBy function. Many projects never used it, so the new syntax makes the choice compulsory. In development mode Angular logs a warning when two items produce the same key.
An example: a class list in which students are re-sorted by marks. With track s.id, the rows move to new positions with their DOM intact. With track $index, the same row elements are reused and their text changes, so an input typed in row 2 would stay in row 2 even though the student moved.
typescript
import { Component, signal } from '@angular/core';
interface Student {
id: number;
name: string;
marks: number;
}
@Component({
selector: 'app-marks-table',
template: `
<button (click)="sort()">Sort by marks</button>
<button (click)="reload()">Reload from server</button>
<ul>
@for (s of students(); track s.id) {
<li>
{{ s.name }}: {{ s.marks }}
<input placeholder="note for {{ s.name }}" />
</li>
}
</ul>
`,
})
export class MarksTableComponent {
students = signal<Student[]>([
{ id: 1, name: 'Asha', marks: 71 },
{ id: 2, name: 'Imran', marks: 88 },
{ id: 3, name: 'Meera', marks: 64 },
]);
sort(): void {
this.students.update((list) => [...list].sort((a, b) => b.marks - a.marks));
}
reload(): void {
// New object instances with the same ids, as an API refresh would return.
this.students.update((list) => list.map((s) => ({ ...s })));
}
}
Angular 20.3. Try swapping `track s.id` for `track $index`, type a note in the first row, then press Sort, and watch where the typed text stays.
Key points
`track` gives each item an identity so DOM nodes can be reused.
Prefer a unique stable id, and avoid tracking whole objects from refreshed API data.
`track $index` is safe only for lists that do not reorder or change in the middle.
It is required in `@for`; `*ngFor` had an optional `trackBy`.
Common mistakes
Using `track $index` on a sortable list with inputs inside rows. Typed values stay at the old row position.
Tracking a field that is not unique, such as `name`. Duplicate keys cause wrong reuse and a development warning.
Using a function call that creates a new object or random value each time, which makes every item look new.
Follow-ups
What happens to the DOM if you track by `item` and replace the array with new objects each poll?
How would you track items that have no id?
How does `@for` behave with an empty array and `@empty`?
Tips
Give the sorted list with typed inputs example. It shows you understand the real effect.
Say what you would do if the API has no id: build a key from stable fields or add one when loading.
Mention that fewer DOM operations also help performance on large lists.
Evaluation rubric
Explains DOM reuse as the purpose.
Prefers a unique id and can name when $index is safe.
Knows the difference from ngFor trackBy.
9.angular-0009Easyfresher
What are directives in Angular, what types exist, and how do you write a custom attribute directive?
A directive adds behaviour to an existing element. Components are directives with a template, attribute directives change how an element looks or acts, and structural directives change the DOM layout by adding or removing elements. A custom attribute directive uses @Directive with an attribute selector and the host property.
Full answer
A directive is a class that Angular attaches to an element in a template to add behaviour. There are three kinds.
Components. A component is a directive that also has a template.
Attribute directives change the look or behaviour of an element, for example NgClass, NgStyle, or your own [appHighlight].
Structural directives add or remove elements, such as *ngIf or *ngFor. These are legacy now, because the built-in control flow (@if, @for) replaced them. You can still write your own structural directive with TemplateRef and ViewContainerRef, and it is used in some libraries.
A custom attribute directive needs a @Directive with a selector in square brackets. Modern code uses the host metadata for listeners and bindings instead of @HostListener and @HostBinding, which still work and are common in older code. Angular's style guide recommends host in new code.
The directive gets the element through inject(ElementRef), and uses input() for options. In the example, hovering over a row changes its background colour.
Directives are the right tool when the same behaviour must be added to many different elements, such as a tooltip, auto-focus, or click-outside detection. A component is better if you also need your own markup.
More points to know:
A directive can expose a template reference with exportAs. Then <div appHighlight #h="appHighlight"> gives the template access to the directive instance and its public members.
Directive inputs work like component inputs, including input.required and transform. Alias the main input to the selector name to allow [appHighlight]="'yellow'".
hostDirectives lets a component or directive attach other directives to its own host and expose chosen inputs. It is a clean way to compose behaviour such as focus handling and tooltips without inheritance.
A structural directive creates or destroys views with ViewContainerRef.createEmbeddedView(templateRef). The * prefix is only shorthand, so *appUnless="x" becomes an ng-template with the directive on it.
A directive has no template and cannot have child content of its own. If you need markup, write a component. If you only transform a value for display, write a pipe.
Directives are standalone by default in current Angular. Add them to the imports of each component that uses them.
Test a directive with a tiny host component in TestBed: create the host, dispatch a mouseenter event on the element, and assert the style.
Angular 20.3. Use it as `<li appHighlight="lightyellow">Asha</li>` in a component that imports HighlightDirective.
Key points
Three kinds: components, attribute directives, structural directives.
`@Directive({ selector: '[appName]' })` creates an attribute directive.
Use `host: { '(event)': 'handler()', '[class.x]': 'expr' }` for listeners and bindings.
Built-in structural directives are legacy; control flow blocks replace them.
Common mistakes
Changing styles by reaching into the DOM through `document.querySelector` instead of the element Angular gives you.
Forgetting to add the directive to the `imports` of the component that uses it.
Choosing a selector that clashes with a native attribute or another library.
Follow-ups
When would you write a directive instead of a component?
How do you apply a directive to an element conditionally?
What does the `host` property replace?
Tips
Prefix selectors (`app`) and say why: it avoids collisions with HTML and libraries.
Mention `host` metadata over `@HostListener` and say the decorators are still valid.
Keep the demo short. Highlight on hover is enough.
Evaluation rubric
Lists three kinds of directives.
Writes a working attribute directive with host listeners.
Knows structural directives are now legacy.
10.angular-0010Easyfresher
What are pipes in Angular, and how do you create a custom pipe?
A pipe transforms a value inside a template, for example formatting a date or a currency amount, with the syntax value | pipeName:arg. Built-in pipes cover common cases, and a custom pipe is a class with @Pipe and a transform method. Pipes are pure by default, so they re-run only when their input changes.
Full answer
A pipe takes a value, changes how it is shown, and returns the result. It does not change the original data. The syntax is {{ value | pipeName:argument }}, and pipes can be chained: {{ name | lowercase | titlecase }}.
Common built-in pipes: date, currency, number, percent, uppercase, lowercase, titlecase, json, slice, keyvalue, and async. Each is a standalone pipe, so you add the ones you use to imports.
To write your own, create a class with @Pipe({ name: 'grade' }) and a transform(value, ...args) method. Implement PipeTransform so TypeScript checks the signature. The pipe is then added to imports of the component that uses it.
Pure and impure pipes:
A pure pipe (the default) runs only when its input value or arguments change by reference or primitive value. This makes it cheap.
An impure pipe (pure: false) runs on every change detection pass. Use it rarely. async is the main built-in example, because it must react to a stream.
Because a pure pipe is checked by reference, passing the same array after push will not re-run a pure pipe that filters the array. Replace the array with a new one, or use a computed signal instead of a filtering pipe.
Pipes are good for display formatting. Do not put heavy filtering or sorting in them, and do not put business rules in them.
Angular 20.3. The date is created with fixed numbers, so the output is the same on every run (the format uses the browser locale, en-US by default).
Key points
`value | pipe:arg` transforms for display only, and pipes can be chained.
Custom pipe: `@Pipe({ name })` plus `transform()`. Add it to `imports`.
Pure pipes run only when inputs change. Impure pipes run on every check.
Prefer `computed` for filtering or sorting data, and pipes for formatting.
Common mistakes
Making a filtering pipe that receives a mutated array. It never re-runs because the reference is the same.
Marking a pipe `pure: false` to fix a stale view, which hides the real bug and slows the app.
Forgetting to add the pipe (including `DatePipe`, `CurrencyPipe`) to `imports`.
Follow-ups
Why is there no built-in filter pipe in Angular?
What does the `async` pipe do and why is it impure?
How would you test a pipe?
Tips
Show that you know pure versus impure. It is the usual follow-up.
Say you format dates and numbers with pipes so they follow the user's locale.
Keep the custom pipe tiny and testable as a plain function.
Evaluation rubric
Writes a working custom pipe with PipeTransform.
Explains pure and impure behaviour.
Imports built-in pipes explicitly.
11.angular-0011Easyfresher
What is a service in Angular, and how does dependency injection with inject() work?
A service is a class that holds shared logic or data. Dependency injection means a component asks for the service instead of creating it, and Angular supplies one instance from an injector. The inject() function reads a service in a class field, and providedIn root makes it a single app-wide instance.
Full answer
A service keeps logic that does not belong to one screen, such as loading data, remembering a logged-in user, or keeping a shopping cart. Components stay small and focus on the template.
Dependency injection (DI) means a class does not create its helpers with new. It asks Angular for them. Angular keeps injectors, which are lookup tables from a token (usually the class itself) to an instance. This makes the code easy to test, because a test can supply a fake service.
To make a service, write a class with @Injectable({ providedIn: 'root' }). This registers it with the root injector, so there is one shared instance in the app, and it is removed from the bundle if nobody uses it (tree-shakable).
To use it, call inject(AttendanceService) in a field initializer or in the constructor. This is the modern form. The older form is constructor parameter injection, constructor(private attendance: AttendanceService) {}, which still works and is very common.
inject() only works in an injection context: field initializers, constructors, and factory functions, not in a random method later.
You can also provide a service in a component's providers array. Then each instance of that component gets its own copy of the service. This is useful for state that belongs to one screen.
Angular 20.3. The service starts with fixed data so the heading always shows the same count.
Key points
A service holds shared logic and data, and is a plain class with `@Injectable`.
`providedIn: 'root'` gives one app-wide, tree-shakable instance.
Use `inject(Service)` in a field or constructor. Constructor parameters are the older, still valid style.
DI helps testing, because a fake can replace the real service.
Common mistakes
Creating a service with `new AttendanceService()`. It bypasses the injector and any dependencies it needs.
Calling `inject()` inside an event handler. It throws outside an injection context.
Providing the same service both in root and in a component by accident, which creates two separate copies of the data.
Follow-ups
How can a component get its own private copy of a service?
What is an injection token?
How would you replace a service with a fake in a test?
Tips
Explain DI without jargon: "the component asks, Angular supplies".
Mention both `inject()` and constructor injection and say which you prefer and why.
Link services to testing. This shows you understand the purpose, not only the syntax.
Evaluation rubric
Explains why DI exists.
Uses providedIn root and inject correctly.
Knows component-level providers create separate instances.
12.angular-0012Easyfresher
How do you set up routing in a standalone Angular app, including route parameters and a wildcard route?
Define a Routes array, register it with provideRouter in the application config, place a router-outlet where pages should appear, and navigate with routerLink. Route parameters are written as :id, and with withComponentInputBinding they arrive directly as component inputs. A "**" route catches unknown URLs.
Full answer
Routing lets one page show different components depending on the URL, without a full page reload.
Set-up has four pieces:
A Routes array maps paths to components: { path: 'courses/:id', component: CourseDetailComponent }.
provideRouter(routes) in the ApplicationConfig providers turns routing on.
<router-outlet /> in a template marks where the matched component is rendered. Import RouterOutlet in that component.
routerLink="/courses" on links navigates without reloading. routerLinkActive="active" adds a CSS class on the current link. Import RouterLink and RouterLinkActive.
Route parameters. In courses/:id, the part after the slash is a parameter. There are two ways to read it: the older ActivatedRoute (route.paramMap observable or route.snapshot.paramMap), or the newer way: add withComponentInputBinding() to provideRouter, and the parameter is bound to an input called id. Query parameters and resolver data can be bound in the same way.
Order matters. The router picks the first match, so the wildcard { path: '**', component: NotFoundComponent } must be last. A redirect from the empty path needs pathMatch: 'full', or it matches every URL.
To navigate from code, inject Router and call router.navigate(['/courses', id]).
Extra points that come up in interviews:
Query parameters and the fragment are separate from path parameters: /courses?level=easy#reviews. Navigate with [queryParams] on routerLink, or router.navigate(['/courses'], { queryParams: { level: 'easy' } }). They stay optional and are not part of the route match.
routerLink accepts an array: [routerLink]="['/courses', course.id]" builds /courses/42 and encodes special characters safely.
Relative links such as routerLink="../" are resolved against the current route, which is useful in nested routes.
Lazy load a page with loadComponent: () => import('./course-detail').then(m => m.CourseDetailComponent). The code for that page is downloaded only when the user visits it.
A title on a route sets the document title, and redirectTo with pathMatch: 'full' sends '' to a default page.
Guards (canActivate) protect routes, and resolvers load data before the page shows. These are separate topics, but a good answer names them.
For a link to show as active, use routerLinkActive and, for the home link, [routerLinkActiveOptions]="{ exact: true }", otherwise / is active on every page.
If a parameter changes while the same component stays on screen (from /courses/1 to /courses/2), Angular reuses the component. With input binding the input updates, so use a computed or effect on it and not ngOnInit.
typescript
// file: app.routes.ts
import { Routes } from '@angular/router';
import { CourseDetailComponent } from './course-detail.component';
import { CourseListComponent } from './course-list.component';
import { NotFoundComponent } from './not-found.component';
export const routes: Routes = [
{ path: '', redirectTo: 'courses', pathMatch: 'full' },
{ path: 'courses', component: CourseListComponent, title: 'Courses' },
{ path: 'courses/:id', component: CourseDetailComponent },
{ path: '**', component: NotFoundComponent },
];
// file: app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withComponentInputBinding())],
};
// file: app.component.ts
import { Component } from '@angular/core';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet, RouterLink, RouterLinkActive],
template: `
<nav>
<a routerLink="/courses" routerLinkActive="active">Courses</a>
</nav>
<router-outlet />
`,
})
export class AppComponent {}
// file: course-list.component.ts
import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';
@Component({
selector: 'app-course-list',
imports: [RouterLink],
template: `<a [routerLink]="['/courses', 42]">Angular basics</a>`,
})
export class CourseListComponent {}
// file: course-detail.component.ts
import { Component, input } from '@angular/core';
@Component({
selector: 'app-course-detail',
template: `<h1>Course {{ id() }}</h1>`,
})
export class CourseDetailComponent {
// Filled from the :id route parameter by withComponentInputBinding().
id = input.required<string>();
}
// file: not-found.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-not-found',
template: `<p>Page not found</p>`,
})
export class NotFoundComponent {}
Angular 20.3. In `main.ts` pass `appConfig` to `bootstrapApplication`. The `id` input is filled from the URL `/courses/42`.
Key points
`provideRouter(routes)` plus `<router-outlet />` plus `routerLink` are the core pieces.
`:id` defines a parameter. `withComponentInputBinding()` delivers it as an input.
First match wins, so put `**` last and use `pathMatch: 'full'` on empty-path redirects.
Navigate in code with `Router.navigate`.
Common mistakes
Using `href` on links. That reloads the whole page and loses app state.
Putting the `**` route first, which makes every route show the not-found page.
Forgetting `pathMatch: 'full'` on a `path: ''` redirect.
Follow-ups
What is the difference between `paramMap` and `snapshot.paramMap`?
How do query parameters differ from route parameters?
How do you make a route lazy loaded?
Tips
Mention `withComponentInputBinding`. It shows you know the current way to read params.
Explain the "first match wins" rule using the wildcard route.
Say that `href` would reload the page, which is the whole reason for `routerLink`.
Evaluation rubric
Names provideRouter, router-outlet, and routerLink.
Reads route parameters in a current way.
Understands route order and pathMatch.
13.angular-0013Easyfresher
What is the difference between template-driven and reactive forms, and how do you build a simple reactive form with validation?
Template-driven forms keep the form model in the template with ngModel and suit small forms. Reactive forms build the model in the class with FormGroup and FormControl, are easier to test and validate, and are the usual choice for larger forms. Validators run on each control and expose errors you can show.
Full answer
Both styles produce the same result, a form with values and validation state. They differ in where the form model lives.
Template-driven forms use directives such as ngModel in the HTML. Angular builds the model behind the scenes. They are quick for a login box, but validation rules are spread through the template and are harder to unit test. They need FormsModule.
Reactive forms build the model in the class. You create FormGroup and FormControl objects (often with FormBuilder), and bind them in the template with [formGroup] and formControlName. They need ReactiveFormsModule. The model is plain code, so you can test it without rendering, read its value as a stream (valueChanges), and change it by code.
Validators are functions. Built-in ones include Validators.required, minLength, min, max, email, and pattern. A control has valid, invalid, touched, dirty, and errors. A good habit is to show an error only after the field is touched, so the user is not shown red text before typing.
Typed forms (Angular 14 and newer) make control.value typed. fb.nonNullable.group({...}) gives string types instead of string | null, which helps with reset() as well.
Rule of thumb: a one or two field form can be template-driven. Anything with dynamic fields, cross-field rules, or serious testing needs should be reactive.
typescript
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-signup',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<label for="email">Email</label>
<input id="email" type="email" formControlName="email" />
@if (form.controls.email.touched && form.controls.email.errors; as errs) {
<small role="alert">
@if (errs['required']) { Email is required. }
@else if (errs['email']) { Enter a valid email. }
</small>
}
<label for="age">Age</label>
<input id="age" type="number" formControlName="age" />
<button type="submit" [disabled]="form.invalid">Join</button>
</form>
`,
})
export class SignupComponent {
private readonly fb = inject(FormBuilder);
readonly form = this.fb.nonNullable.group({
email: ['', [Validators.required, Validators.email]],
age: [18, [Validators.required, Validators.min(16), Validators.max(100)]],
});
submit(): void {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
const { email, age } = this.form.getRawValue();
console.log(`Registered ${email}, age ${age}`);
}
}
Angular 20.3, strict template type-checking passes. The submit handler uses `getRawValue()` so it is also typed.
Key points
Template-driven: model in the template, `ngModel`, `FormsModule`. Reactive: model in the class, `FormGroup`, `ReactiveFormsModule`.
Validators are functions and set `errors` on the control.
Show errors after `touched` or `dirty`, not on first render.
`fb.nonNullable` gives non-null types in typed forms.
Common mistakes
Importing `FormsModule` when the template uses `formGroup`. It needs `ReactiveFormsModule`.
Mixing `ngModel` and `formControlName` on the same input.
Checking `form.valid` once in the constructor instead of in the template or on submit.
Follow-ups
How do you write a custom validator?
What is the difference between `setValue` and `patchValue`?
When does `updateOn: 'blur'` help?
Tips
Give the practical rule for choosing between them instead of listing features.
Mention that typed forms exist. It shows you are current.
Always add accessible error messages next to the field, and say so.
Evaluation rubric
Explains where each model lives.
Builds a reactive form with validators and error display.
Knows typed form basics.
14.angular-0014Easyfresher
How do you call an API with HttpClient in a standalone Angular app, and how do you handle the response and errors?
Register provideHttpClient in the application config, inject HttpClient in a service, and call get, post, put or delete with a response type. These return cold Observables that send the request when subscribed. Show the data with the async pipe and handle errors with catchError.
Full answer
HttpClient is Angular's built-in tool for calling REST APIs. In a standalone app, add provideHttpClient() to the application config. In an NgModule app (legacy) you imported HttpClientModule instead, which is deprecated.
Calls return Observables:
ts
this.http.get<Course[]>('/api/courses');
The type argument only tells TypeScript the expected shape. It does not check the data at runtime. If the server sends something different, the compiler cannot warn you.
The request is sent when something subscribes, and each subscription sends a new request. In a template, the async pipe subscribes and unsubscribes for you. The Observable completes after the response, so there is no leak from one-shot HTTP calls.
Error handling. A failed request errors the Observable with an HttpErrorResponse. Use catchError to show a message or return a fallback value: catchError(() => of([])). Status code 0 means the request never reached a server (network, CORS, or offline).
Good habits: keep HTTP calls in a service, not in the component; set the API base URL in one place; and use withFetch() in provideHttpClient if you use server-side rendering, as it uses the Fetch API.
Other verbs: post<T>(url, body), put, patch, delete. Query parameters go in { params: { page: 2 } }, headers in { headers: {...} }.
Angular 20.3. Replace the URL with a real endpoint. The code has a service, a component, and the config in one file set.
Key points
`provideHttpClient()` enables HttpClient. `HttpClientModule` is legacy.
Calls are cold Observables, so nothing is sent until you subscribe.
The generic type is a compile-time hint, not runtime validation.
Handle failures with `catchError`, and keep calls inside a service.
Common mistakes
Calling `http.get(...)` and forgetting to subscribe, so no request is sent.
Subscribing twice (for example the same observable with two `async` pipes) and sending two requests.
Trusting the generic type as proof the server data is valid.
Follow-ups
How would you avoid sending the same request twice from one template?
What does an interceptor do?
How do you cancel an in-flight request?
Tips
Say that the generic does not validate data. Many candidates miss this.
Mention status 0 and what it usually means.
Offer `withFetch()` if SSR comes up.
Evaluation rubric
Registers HttpClient with provideHttpClient.
Understands cold observables and subscription.
Handles errors without hiding them.
15.angular-0015Easyfresher
What are the main Angular lifecycle hooks, in what order do they run, and what is the difference between the constructor and ngOnInit?
Hooks are methods Angular calls at set moments in a component's life. The main order is constructor, ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterViewInit, then ngOnDestroy on removal. The constructor only builds the object and injects dependencies, while ngOnInit runs once after the first inputs are set.
Full answer
Angular creates a component, updates it as data changes, and later destroys it. Hooks let your code run at those moments. Implement the matching interface (OnInit, OnDestroy) and add the method.
Order for one component:
constructor: the class is created. Use it for dependency injection and simple field setup only.
ngOnChanges: runs when a decorator-based @Input changes, before ngOnInit and on each later change. It receives a SimpleChanges object.
ngOnInit: runs once, after the first ngOnChanges. The inputs are ready here. A good place to start loading data.
ngDoCheck: runs on every change detection pass. Use it rarely.
ngAfterContentInit and ngAfterContentChecked: after projected content (<ng-content>) is ready.
ngAfterViewInit and ngAfterViewChecked: after the component's own view and children are ready. View queries are available here.
ngOnDestroy: just before removal. Clean up timers, subscriptions, and listeners.
The constructor versus ngOnInit question: at constructor time, the inputs have not been set. Keep the constructor free of work so tests can build the class easily.
Modern additions. With signal inputs, you do not need ngOnChanges: use computed or effect. For code that must touch the DOM after rendering, use afterNextRender and afterEveryRender (stable from Angular 20) instead of ngAfterViewInit. They do not run on the server, so they are SSR-safe. For cleanup, inject(DestroyRef).onDestroy(...) can replace ngOnDestroy.
Angular 20.3. `OnChanges` is shown with a decorator input on purpose, because that is the only input style that triggers it. Open the console to see the order of log lines.
Inputs are available in `ngOnInit`, not in the constructor.
Clean up in `ngOnDestroy` or with `DestroyRef`.
`afterNextRender` is the modern, SSR-safe hook for DOM work.
Common mistakes
Reading `@Input` values in the constructor and getting `undefined`.
Starting a `setInterval` and never clearing it in `ngOnDestroy`.
Doing heavy work in `ngDoCheck`, which runs on every pass.
Follow-ups
Why does `ngOnChanges` not run for signal inputs?
Where would you access a `viewChild` safely?
What is the difference between `ngAfterContentInit` and `ngAfterViewInit`?
Tips
Do not recite all eight hooks with no use. Name three or four and say what each is for.
Mention `afterNextRender` and `DestroyRef`. This shows modern knowledge.
Always mention cleanup. It is what interviewers actually care about.
Evaluation rubric
Gives the correct order of main hooks.
Explains constructor versus ngOnInit.
Mentions cleanup and modern alternatives.
16.angular-0016Easyfresher
What is an Observable, and how does it differ from a Promise? Why do you need to unsubscribe?
A Promise delivers one value, starts immediately, and cannot be cancelled. An Observable can deliver many values over time, is lazy (it starts on subscribe), can be cancelled by unsubscribing, and has operators to transform the stream. Long-lived Observables must be unsubscribed to avoid memory leaks.
Full answer
Both represent work that finishes later, such as an API call. The differences matter in practice.
A Promise:
gives exactly one result or one error;
is eager. The work starts when the Promise is created;
cannot be cancelled;
is consumed with then or await.
An Observable (from RxJS, which Angular uses for HTTP, router events, and forms):
can give zero, one, or many values, then complete or error;
is lazy. Nothing happens until subscribe();
each subscriber normally gets its own execution (cold);
can be cancelled, because subscribe() returns a Subscription with unsubscribe();
has many operators such as map, filter, debounceTime, and switchMap.
An everyday picture: a Promise is a single exam result slip. An Observable is a live cricket score feed. It keeps sending updates until it ends or you stop listening.
Why unsubscribe? A stream such as interval(1000) or a form's valueChanges never completes by itself. If a component is destroyed while still subscribed, the callback keeps running and holds the component in memory (a leak). HTTP observables complete after one response, so they need no manual cleanup. Safe options: the async pipe, takeUntilDestroyed(), or take(1) and first() for one value.
You can convert between them: firstValueFrom(obs$) and lastValueFrom(obs$) give a Promise, and from(promise) gives an Observable.
typescript
import { Observable, firstValueFrom, interval, take } from 'rxjs';
// A Promise starts immediately.
const promise = new Promise<number>((resolve) => {
console.log('promise runs now');
resolve(1);
});
// An Observable does nothing until subscribe().
const numbers$ = new Observable<number>((subscriber) => {
console.log('observable started');
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
subscriber.complete();
});
console.log('observable not started');
numbers$.subscribe({
next: (n) => console.log('value', n),
complete: () => console.log('done'),
});
// A never-ending stream must be stopped.
const ticks: number[] = [];
const sub = interval(20).subscribe((n) => ticks.push(n));
setTimeout(() => {
sub.unsubscribe();
console.log('stopped after', ticks.length, 'ticks');
}, 50);
console.log('promise value', await promise);
console.log('first value', await firstValueFrom(interval(5).pipe(take(1))));
Tested with RxJS 7 and Node 22.18 or newer (`node main.ts`, with a `type: module` package.json). The output is the same on every run. Output: `promise runs now`, `observable not started`, `observable started`, `value 1`, `value 2`, `value 3`, `done`, `promise value 1`, `first value 0`, and finally `stopped after 2 ticks`.
Key points
Promise: one value, eager, no cancel. Observable: many values, lazy, cancellable.
Nothing runs until `subscribe()`; each subscription usually runs the source again.
Unsubscribe from streams that do not complete. HTTP completes by itself.
`firstValueFrom` and `from` convert between the two.
Common mistakes
Saying Observables are always asynchronous. `of(1, 2, 3)` emits synchronously.
Subscribing in a component and never cleaning up an `interval` or `valueChanges` subscription.
Using `toPromise()`, which was deprecated in RxJS 7 and removed in RxJS 8. Use `firstValueFrom` or `lastValueFrom`.
Follow-ups
What does cold versus hot mean?
When would you prefer `firstValueFrom` over subscribing?
How does the async pipe prevent leaks?
Tips
Use the table of differences: values, laziness, cancellation, operators. It is a clear structure.
Say that cancellation is the biggest practical advantage, for example cancelling a search request.
Mention `takeUntilDestroyed`, because it is the modern answer to cleanup.
Evaluation rubric
States lazy versus eager and one versus many values.
Can explain why unsubscribing matters.
Knows how to convert and clean up.
17.angular-0017Easyfresher
What are template reference variables, and how do you access an element or child component from the class with viewChild()?
A template reference variable, written #name, gives the template a handle to an element, component, or directive. From the class you can read it with the viewChild() signal query (or the older @ViewChild decorator). The query result is available after the view is created and is undefined for content inside a false @if.
Full answer
A reference variable names something in the template: <input #nameInput />. Anywhere in the same template you can use nameInput to read its properties, for example nameInput.value. On a component tag, the variable refers to the component instance. On a plain element, to the DOM element.
To reach the same thing from the TypeScript class, use a view query:
viewChild<ElementRef<HTMLInputElement>>('nameInput') returns a signal that holds the element reference or undefined.
viewChild.required(...) throws if the result is missing when read.
viewChild(ChildComponent) finds a child by type.
viewChildren(...) returns a signal of all matches.
Signal queries (stable since Angular 19) update automatically, so you can use them in computed and effect. The older decorators, @ViewChild and @ViewChildren, still work. They filled the field at a later time, and you had to wait for ngAfterViewInit.
When is the result ready? After the first render. In the constructor or ngOnInit the signal returns undefined. If the element is inside @if or @for, it appears and disappears with the block.
Use queries sparingly. Prefer data binding. A good reason is to call focus(), to scroll an element into view, or to call a method on a child.
Related: contentChild and contentChildren read items projected into <ng-content>.
Angular 20.3, strict template check passes. Clicking the button moves the cursor to the input.
Key points
`#ref` names an element or component in a template.
`viewChild()` and `viewChildren()` are signal queries; `@ViewChild` is the older decorator.
Results are `undefined` until the view is rendered, and when the element is inside a false `@if`.
Use queries for focus, scrolling, and calling child methods, not for ordinary data flow.
Common mistakes
Reading the query in the constructor and getting `undefined`.
Changing the DOM directly with `nativeElement.innerHTML` when a binding would do.
Using `viewChild` for an element inside a false `@if` and not checking for `undefined`.
Follow-ups
What is the difference between `viewChild` and `contentChild`?
When can you safely read a query result?
How do you read a directive instance instead of the element?
Tips
Use the focus-on-click example. It is the most realistic use.
Mention that you reach for data binding first, and queries only when needed.
Know the `read` option for picking `ElementRef` or `ViewContainerRef` from a tag.
Evaluation rubric
Explains reference variables and signal queries.
Knows when results are available.
Gives a reasonable use case.
18.angular-0018Mediummid
What is change detection in Angular, how does OnPush differ from Default, and when does an OnPush component re-render?
Change detection is how Angular finds what changed and updates the DOM. With Default, every component is checked after each event. With OnPush, a component is checked only when an input reference changes, an event fires inside it, an async pipe or signal read in its template changes, or markForCheck is called.
Full answer
Change detection compares the data the templates use with what is on screen and updates the DOM where they differ. In an app with zone.js, Angular runs this after every browser task that could have changed data: a click, a timer, an HTTP response. Zone.js tells Angular that such a task finished.
With the Default strategy the whole tree of components is checked from the top each time. That is simple and correct, but wasteful for large screens.
ChangeDetectionStrategy.OnPush tells Angular to skip a component (and its children) unless a reason to check appears. The reasons are:
An input binding got a new value by reference (!==). Mutating an object in place is not a change.
An event listener in the component's own template ran, such as (click).
The async pipe received a new value.
A signal read in the template changed.
Code called ChangeDetectorRef.markForCheck() or detectChanges().
So with OnPush you treat data as immutable. Instead of student.marks += 5, you write student = { ...student, marks: student.marks + 5 }. This is a good habit anyway, and it makes the checks cheap.
Signals make this easier. A component that reads signals in its template is updated when those signals change, even if it is OnPush. Writing components that work with OnPush is also the best preparation for zoneless apps. In Angular 20 a generated component is still Default unless you ask for OnPush, so set it yourself.
Angular 20.3. Click Mutate: the card stays at 70. Click Replace: the card updates. Angular warns nothing in the mutate case, which is the point of the example.
Key points
Default checks every component on each event; OnPush checks only when it has a reason.
OnPush triggers: new input reference, own event, async pipe, changed signal, `markForCheck`.
Mutating an object that was passed in does not update an OnPush child.
Immutable updates and signals work naturally with OnPush.
Common mistakes
Mutating an array or object passed to an OnPush child and wondering why the view is stale.
Calling `detectChanges()` everywhere to patch a stale view, instead of fixing the data flow.
Believing OnPush stops the whole app from updating. It only skips components that have no trigger.
Follow-ups
What does `markForCheck` do that `detectChanges` does not?
How does zone.js know when to start change detection?
How does a signal read in an OnPush template trigger an update?
Tips
List the five triggers. An interviewer often asks for all of them.
Use the object-mutation example. It is the classic OnPush bug.
Mention signals and zoneless as the direction Angular is going.
Evaluation rubric
Lists OnPush triggers correctly.
Explains why mutation breaks OnPush.
Connects OnPush to immutability and signals.
19.angular-0019Mediummid
What is effect() in Angular, when should you use it, and what mistakes should you avoid?
effect() runs a function once and again whenever the signals it read change. It is for side effects that leave the signal world, such as logging, storage, or talking to a non-Angular library. It should not be used to copy one signal into another, because computed or linkedSignal do that better.
Full answer
An effect is a function that Angular runs at least once, records which signals it reads, and runs again when any of them change. Effects are created in an injection context, usually a constructor or field initializer, and are destroyed with their owner.
Good uses are side effects that Angular cannot do with bindings: writing to localStorage, sending an analytics event, drawing on a canvas, or updating a third-party widget. Read the signals, do the outside work, done.
Bad use: deriving state. Code like effect(() => this.total.set(this.a() + this.b())) is a mistake. A computed does it without an extra pass. For a value that is derived but can also be changed by the user, use linkedSignal.
Details worth knowing:
Effects run asynchronously as part of change detection, not at the moment of set. Several changes in a row run the effect once.
Only signals read synchronously during the run are tracked. Reads after an await or in a callback are not tracked.
untracked(() => ...) reads a signal without making it a dependency.
The callback receives onCleanup, to register work that must run before the next run or when the effect is destroyed, such as clearing a timer.
Writing to signals inside an effect is allowed since Angular 19 (the old allowSignalWrites flag is no longer needed), but it often hides a design problem.
Effects are stable in Angular 20. For DOM work after rendering, use afterRenderEffect.
typescript
import { Component, effect, inject, signal, untracked } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-theme-switch',
template: `
<button (click)="toggle()">Theme: {{ theme() }}</button>
<button (click)="addClick()">Clicks: {{ clicks() }}</button>
`,
})
export class ThemeSwitchComponent {
private readonly title = inject(Title);
readonly theme = signal<'light' | 'dark'>('light');
readonly clicks = signal(0);
constructor() {
effect((onCleanup) => {
const current = this.theme();
// Read without making the effect depend on clicks.
const seen = untracked(this.clicks);
this.title.setTitle(`Theme: ${current}`);
const timer = setTimeout(() => console.log('theme', current, 'after', seen, 'clicks'), 500);
onCleanup(() => clearTimeout(timer));
});
}
toggle(): void {
this.theme.update((t) => (t === 'light' ? 'dark' : 'light'));
}
addClick(): void {
this.clicks.update((c) => c + 1);
}
}
Angular 20.3. Setting the page title is a harmless, visible side effect, so it is used here. The log shows the theme and the click count, but only a theme change reruns the effect.
Key points
An effect reruns when the signals it read change, and runs at least once.
Use effects for side effects (storage, logging, widgets), not for derived state.
Only synchronous reads are tracked; use `untracked` to opt out.
`onCleanup` removes timers and listeners before the next run.
Common mistakes
Copying one signal into another in an effect. Use `computed` or `linkedSignal`.
Reading a signal after an `await` and expecting it to be tracked.
Creating an effect outside an injection context without passing an `injector`. It throws.
Follow-ups
Why does an effect not run immediately after `set`?
How would you create an effect inside a method?
What is the difference between `effect` and `afterRenderEffect`?
Tips
State the rule: effects are for leaving the signal graph, not for staying in it.
Show `untracked` and `onCleanup`. They show you have used effects in real code.
If asked about RxJS, say effects are not a replacement for streams that need operators like `debounceTime`.
Evaluation rubric
Understands tracking and asynchronous scheduling.
Gives correct good and bad uses.
Mentions untracked and cleanup.
20.angular-0020Mediummid
What is linkedSignal, and how is it different from computed()?
computed() is read-only and always follows its sources. linkedSignal() is also derived from a source, but you can write to it. When the source changes, it is recalculated, so it resets to a sensible default. It fits state such as a selected item that must reset when its list changes.
Full answer
A computed is perfect for values that are only derived: a total, a grade, a filtered list. You cannot set it.
Sometimes a value is derived by default but the user can override it. Example: a list of courses and a "selected course". The selection starts as the first course. The user can pick another one. When the list is replaced by a new list, the old selection may no longer exist, so the selection should reset.
Before linkedSignal this needed an effect that wrote to a normal signal, which is the pattern to avoid. linkedSignal solves it:
It behaves like a writable signal. selected.set('RxJS') works. When courses changes, the computation runs again with the new source value and the previous state, so you decide whether to keep the user's choice or reset it.
The short form linkedSignal(() => this.courses()[0]) recomputes whenever any signal it reads changes, and the user's own set is lost at that moment.
Both are lazy and cached. linkedSignal became stable in Angular 20.
Some details that make the answer complete:
In the long form, the computation function receives the new source value and a previous object with source and value. In the example, this lets you keep the same selection if the item still exists in the new list.
The short form has no source. It re-runs whenever any signal that it read changes, and the writes the user made before are replaced.
A second example is pagination. A page linked to the filter signal goes back to 1 when the filter changes, but the user can still press "next" and set the page.
linkedSignal accepts an equal function, like computed, to avoid updates when the new value is considered equal.
Do not use an effect that sets another signal for this job. An effect runs later and can show an old value for one render. linkedSignal updates when it is read, so there is no stale value.
Choose computed when the value must never be changed by the user, linkedSignal when the value has a default from other state but can be edited, and a plain signal when the value does not depend on anything.
typescript
import { linkedSignal, signal } from '@angular/core';
const courses = signal(['Angular', 'RxJS', 'TypeScript']);
const selected = linkedSignal<string[], string>({
source: courses,
computation: (list, previous) =>
previous && list.includes(previous.value) ? previous.value : list[0],
});
console.log(selected()); // Angular
selected.set('RxJS');
console.log(selected()); // RxJS
// New list still contains RxJS: the user's choice is kept.
courses.set(['RxJS', 'Signals']);
console.log(selected()); // RxJS
// New list no longer contains it: reset to the first item.
courses.set(['Testing', 'Routing']);
console.log(selected()); // Testing
Tested with Angular 20.3 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`). Output is identical on repeated runs: `Angular`, `RxJS`, `RxJS` (kept), `Testing` (reset).
Key points
`computed` is read-only; `linkedSignal` is writable and derived.
The `source` plus `computation(source, previous)` form lets you keep the old value when it is still valid.
Setting a linked signal works until the source changes, then it recomputes.
Replaces the "effect that sets another signal" pattern.
Common mistakes
Using an effect to reset a selection when data changes.
Using `computed` and then trying to call `set` on it.
Ignoring `previous` and always resetting, which throws away the user's valid choice.
Follow-ups
What is the type of `previous` in the computation function?
How is this different from a `model()` input?
Can you give a form-related example?
Tips
Use the selected-item example. It is the clearest story.
Say "derived but overridable" in one sentence. It is a good summary.
Mention that you replaced an effect with it, and why that is safer.
Evaluation rubric
Distinguishes read-only from writable derived state.