Questions 101–120 of 195 · 0 of 20 on this page marked learned
101.angular-0101Easyfresher
How does Angular compare with React and Vue, and how would you choose between them for a project?
Angular is a full framework with routing, forms, HTTP, DI and testing included, written in TypeScript. React is a UI library that needs other libraries for the rest, and Vue sits in between with an official router and state library. The choice depends on team size, existing skills, the need for conventions, and hiring.
Full answer
All three build component based user interfaces and all three now use fine-grained reactivity ideas (Angular signals, Vue refs, React state with hooks), but they differ in scope and style.
Angular is a complete framework. The CLI, router, forms (template-driven and reactive), HttpClient, dependency injection, animations support, testing tools and an official style guide are included and versioned together. It uses TypeScript by default, templates are separate HTML syntax compiled ahead of time, and there is a strong convention for structure. This suits large teams and long-lived applications, because every project looks similar.
React is a library for rendering UI. It uses JSX, so templates are JavaScript, and state is handled with hooks. Routing, data fetching, forms and state management come from other libraries (or from a meta framework such as Next.js). It gives freedom and a very large ecosystem, but each team must decide and maintain its own stack.
Vue is a progressive framework. It uses single file components with a template, script and style in one file, an official router (Vue Router) and state library (Pinia), and a gentle learning curve. It is common in small and medium products.
Points to compare:
Learning curve: Vue is easiest, React is simple at first but ecosystem choices add work, Angular has the most concepts (DI, modules or standalone, RxJS, decorators).
Change detection: Angular uses zones or signals, React re-renders components from state changes and compares a virtual DOM, Vue tracks reactive dependencies.
Typing: Angular is TypeScript first. React and Vue both support TypeScript well.
Long term: Angular has a predictable release schedule and ng update migrations.
A good answer ends with a rule: choose the tool your team can maintain, not the one that wins arguments online.
Conceptual comparison for Angular 20, React 19 and Vue 3. The sample shows the same counter in Angular with a signal. It was type-checked, and a Karma test clicks the button and checks the text.
Key points
Angular is a full framework with conventions. React is a view library. Vue is in between.
Angular is TypeScript first, uses DI, RxJS and signals, and has the steepest learning curve.
React gives freedom and a huge ecosystem but needs more decisions.
Choose by team skills, project size, hiring and long-term maintenance.
Common mistakes
Saying one framework is "faster" without measuring a real case.
Comparing Angular with React as if both were the same kind of tool.
Ignoring team experience when choosing.
Follow-ups
How would you compare state management in the three?
How does server side rendering differ across them?
What would make you pick Angular for an enterprise dashboard?
Tips
Start with the difference in scope (framework vs library).
Stay fair. Name a real strength of each.
End with a decision rule based on the team.
Evaluation rubric
Explains the scope difference correctly.
Gives balanced trade-offs on learning curve, typing and ecosystem.
Ends with a practical decision approach.
102.angular-0102Easyfresher
What is the difference between an HTML attribute and a DOM property, and which binding gotchas does this cause in Angular templates?
An attribute is what you write in HTML and sets an initial value, while a property is the live value on the DOM object. Angular property binding sets properties, so [value] changes what the user sees, but some things only exist as attributes (aria-*, colspan), and these need [attr.name].
Full answer
When the browser reads <input value="Asha"> it creates a DOM object. The attribute value="Asha" is only the initial value. The property input.value is the current value, and it changes when the user types. The attribute does not change.
Angular bindings work with properties, not attributes:
[value]="name" sets input.value. Interpolation value="{{ name }}" does the same thing, because Angular turns it into a property binding.
[disabled]="isLocked" sets button.disabled to true or false. The attribute disabled="false" in plain HTML still disables the button, because only the presence of the attribute matters. That is why you must bind with brackets and never write disabled="{{ flag }}" expecting a boolean.
Things with no matching property need an attribute binding with the attr. prefix:
[attr.aria-label]="label" and other ARIA attributes.
[attr.colspan]="span" (the DOM property is colSpan, with a capital S, and not every table attribute has a property).
[attr.data-id]="id". Setting the value to null removes the attribute.
Other gotchas:
Interpolation always converts to a string, so title="{{ count }}" gives "5". A property binding passes the real type: [maxLength]="5" passes a number.
Binding to an unknown property is a compile error: Can't bind to 'foo' since it isn't a known property. This often means a missing import in a standalone component.
A plain attribute with no brackets passes a fixed string: <app-card size="3"> gives the string "3", and [size]="3" gives the number 3.
Class and style have special bindings: [class.active]="isActive" and [style.width.px]="width".
Angular 20.3, strict template check passes. A Karma test checks the ARIA attribute value, that the attribute is removed when the value is null, and the colspan attribute.
Key points
Attributes set initial values. Properties are the live DOM state. Angular binds properties.
Use `[attr.name]` for attributes without a property, such as `aria-*`.
Interpolation produces strings. Property binding keeps the type.
Without brackets, an input receives a literal string.
Common mistakes
Writing `disabled="{{ flag }}"` or `disabled="false"` and wondering why the control stays disabled.
Forgetting `attr.` for ARIA attributes.
Passing `size="3"` to a numeric input and getting the string "3".
Follow-ups
What happens when you bind `[attr.title]` to `null`?
Why does `[value]` update the input but the `value` attribute stay the same?
How would you pass a number to a component input from a template?
Tips
Use the `<input value>` example. It makes the difference clear in one line.
Mention `attr.` for accessibility attributes.
Mention the string versus typed value difference.
Evaluation rubric
Defines attribute and property correctly.
Names `[attr.x]` use cases and the boolean attribute trap.
Knows interpolation gives strings.
103.angular-0103Easyfresher
In what order do the lifecycle hooks run for a parent and a child component, including content projection?
For a parent and its child, constructors and ngOnInit run parent first, and the after-view hooks run child first: the child's ngAfterViewInit completes before the parent's. Content projected into a component is initialised before that component's view.
Full answer
Order matters in interviews because it explains why some values are not available yet.
For one component the sequence is: constructor, ngOnChanges (only if it has inputs that were set), ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked. ngOnChanges and ngOnInit run once per input change and once per creation. ngDoCheck and the two Checked hooks run on every change detection pass. ngOnDestroy runs when the component is removed.
With a parent and a child in the parent's template, the order was captured from a real run (Angular 20, one parent, one child with one input):
Parent constructor, then child constructor. Angular creates the parent's view first, and that creates the child object, before any ngOnInit runs.
Parent ngOnInit, then parent ngAfterContentInit (the parent has no projected content, so this comes right away).
Child ngOnChanges, ngOnInit, ngAfterContentInit. Input values reach the child during the parent's update pass.
Child ngAfterViewInit.
Parent ngAfterViewInit.
Do not memorise every step. Remember three rules: constructors run top down and early, ngOnInit runs top down, and the "after view" hooks run bottom up.
So initialisation goes top down, and the "after view" hooks go bottom up. The parent's ngAfterViewInit is the first place where viewChild queries for children are filled and the children are fully rendered.
With content projection (<app-card><app-badge /></app-card>), the projected app-badge is created by the host template's component, and the card's ngAfterContentInit runs after the badge exists. The card's own view hooks run after that.
Practical consequences:
Do not read inputs in the constructor. They are set before ngOnInit.
Do not read viewChild before ngAfterViewInit (signal queries are available after the first render).
Changing a parent value inside a child's ngAfterViewInit can cause ExpressionChangedAfterItHasBeenChecked in development mode.
Angular 20.3. The components log each hook. The order in the code comment is the one captured from a Karma run in headless Chrome, and an assertion in that test checks it.
Key points
Per component: constructor, ngOnChanges, ngOnInit, ngDoCheck, content hooks, view hooks.
Constructors and ngOnInit run parent first. Child "after view" hooks finish before the parent's.
Projected content is ready before the host's `ngAfterContentInit`.
Read inputs in `ngOnInit`, and view queries after view init.
Common mistakes
Reading `@Input` values in the constructor.
Expecting the parent's `ngAfterViewInit` to run before the child's.
Changing bound state in an `After...Checked` hook without care.
Follow-ups
Why does `ngOnChanges` not run for a component with no inputs?
What causes ExpressionChangedAfterItHasBeenChecked?
Where would you start a timer and where would you stop it?
Tips
Draw the two-level sequence in your answer.
Say which hooks repeat on every pass.
Link the order to a real bug (reading a query too early).
Evaluation rubric
Gives the correct per-component sequence.
Gets parent and child ordering right.
Explains consequences for inputs and queries.
104.angular-0104Easyfresher
What is the difference between the constructor and ngOnInit, and what should go in each?
The constructor is a TypeScript class feature that runs when the object is created and is used for dependency injection and simple field setup. ngOnInit is an Angular hook that runs once after the first inputs are set, so it is the place for start-up logic that needs input values.
Full answer
The constructor belongs to JavaScript and TypeScript. It runs when Angular creates the component instance. At that moment Angular has injected the dependencies, but it has not yet set the input values, and the template has not been rendered.
ngOnInit is a lifecycle hook that Angular calls once, after it has set the initial input values and before the first rendering of the template. It is the place for initialisation that depends on inputs or needs to start work, such as loading data for an id input.
Guidelines:
Constructor: receive injected services (or use inject()), set up simple fields, create effects and toSignal values that need an injection context. Keep it fast and free of side effects such as HTTP calls.
ngOnInit: use input values, call services to load data, subscribe to streams that depend on inputs.
ngOnDestroy (or DestroyRef): clean up.
Why not do everything in the constructor?
Inputs are not set yet, so a classic @Input is undefined, and reading a required signal input throws (the compiler even reports this as error NG8118).
Testing is harder, because creating the class starts work.
Angular promises the hook order. The constructor order is just object creation.
With signal inputs the picture changes a little: input() reads are reactive, so you can use computed, effect, or resource with the input and do not need ngOnInit for many cases. For example resource({ params: () => this.id(), loader }) reloads automatically when the input changes.
ngOnInit runs only once. If the input changes later, use ngOnChanges, a computed, or an effect.
typescript
import { Component, Input, OnInit, inject, input } from '@angular/core';
export class MarksService {
load(id: number): string {
return `marks for student ${id}`;
}
}
@Component({
selector: 'app-student-marks',
providers: [MarksService],
template: `<p>{{ text }}</p>`,
})
export class StudentMarksComponent implements OnInit {
private readonly service = inject(MarksService);
readonly id = input.required<number>(); // signal input
@Input() legacyId?: number; // classic input
text = '';
legacyInConstructor: number | undefined;
constructor() {
this.legacyInConstructor = this.legacyId; // undefined: inputs are not set yet
// this.id() here would be rejected by the compiler (NG8118).
}
ngOnInit(): void {
this.text = this.service.load(this.id()) + ' / legacy ' + this.legacyId;
}
}
Angular 20.3, strict template check passes. A Karma test checks that the classic input is undefined in the constructor and that ngOnInit sees the signal input value. The compiler rejects reading the required signal input in the constructor, as the text says.
Key points
The constructor runs at creation, with dependencies but without input values.
`ngOnInit` runs once after the first inputs are set.
Keep constructors light. Start loading in `ngOnInit` or with signals and `resource`.
Signal inputs reduce the need for `ngOnInit`.
Common mistakes
Reading an `@Input` in the constructor and getting `undefined`.
Making HTTP calls in the constructor, which makes tests and creation heavy.
Expecting `ngOnInit` to run again when an input changes.
Follow-ups
When would you use `ngOnChanges` instead?
How does `inject()` compare with constructor parameters?
How would a `resource` replace `ngOnInit` loading code?
Tips
State clearly what is available in each (dependencies versus inputs).
Mention signal inputs to show current knowledge.
Give the "load by id" example.
Evaluation rubric
Explains the difference in timing and responsibility.
Gives practical guidance on what goes where.
Knows `ngOnInit` runs once.
105.angular-0105Easyfresher
How does two-way binding work in Angular, and how do [(ngModel)] and model() relate to property and event binding?
Two-way binding is a shortcut for a property binding plus an event binding. [(x)]="value" means [x]="value" (xChange)="value = $event". ngModel uses this for form controls, and a component can offer it with a model() signal or an input plus an output named xChange.
Full answer
Two-way binding keeps a parent value and a child control in sync. The syntax [(x)]="value" is nicknamed "banana in a box". It is only sugar for two bindings:
[x]="value" (xChange)="value = $event"
The child must therefore have an input x and an output named xChange. Angular does not do anything magical. The parent value flows down through the input, and when the child emits xChange, the parent assigns the new value.
ngModel (from FormsModule) is the best known case. [(ngModel)]="name" sets the control value from name, and updates name on every input event. It works with a ControlValueAccessor behind the scenes, so it works with inputs, selects, checkboxes and custom controls.
Custom two-way binding in a component:
Modern way: value = model(0) creates a writable signal that is also an input and an output (valueChange). Use [(value)]="parentSignal", where the parent can pass a signal directly. Inside, this.value.set(5) updates the parent.
Classic way: an @Input() value plus an @Output() valueChange = new EventEmitter().
Notes:
With a signal in the parent, bind with [(value)]="score" where score is a WritableSignal. Angular reads and writes it for you in a two-way binding.
You cannot use two-way binding on an expression that cannot be assigned, for example a function call or a pipe.
For forms with validation, prefer reactive forms. ngModel is simple but gives less control, and mixing ngModel with formControl on the same element is not allowed.
Two-way binding hides data flow. In large apps, prefer one-way down and events up, using two-way only for small form-like components.
typescript
import { Component, model, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-stepper',
template: `
<button (click)="value.set(value() - 1)">-</button>
{{ value() }}
<button (click)="value.set(value() + 1)">+</button>
`,
})
export class StepperComponent {
readonly value = model(0); // input "value" + output "valueChange"
}
@Component({
selector: 'app-two-way-demo',
imports: [StepperComponent, FormsModule],
template: `
<app-stepper [(value)]="marks" />
<p>Marks: {{ marks() }}</p>
<input [(ngModel)]="name" name="first" />
<!-- long form of the line above: -->
<input [ngModel]="name" (ngModelChange)="name = $event" name="second" />
<p>{{ name }}</p>
`,
})
export class TwoWayDemoComponent {
readonly marks = signal(10);
name = 'Asha';
}
Angular 20.3, strict template check passes. A Karma test clicks the child button and checks that the parent signal and the parent text change.
Key points
`[(x)]` equals `[x]` plus `(xChange)`.
`ngModel` is the standard form directive using this pattern. It needs `FormsModule`.
`model()` creates a signal that is both input and output.
Prefer one-way data flow for large state.
Common mistakes
Forgetting to import `FormsModule` and getting an error about `ngModel`.
Naming the output incorrectly, so `[(x)]` does not work.
Using two-way binding on an expression that cannot be assigned.
Follow-ups
How would you write the long form of `[(ngModel)]`?
How does `model()` differ from `input()` plus `output()`?
Why mix `ngModel` and reactive forms carefully?
Tips
Show the expanded form. It proves you understand it.
Mention `model()` as the modern option.
Add a sentence on one-way flow as the default.
Evaluation rubric
Explains the banana syntax as two bindings.
Knows ngModel, model(), and the classic pair.
Mentions trade-offs.
106.angular-0106Easyfresher
What is the difference between ng-container, ng-template and ng-content, and when do you use each?
ng-container is a grouping element that adds nothing to the DOM, ng-template defines a template that is not rendered until something instantiates it, and ng-content is a slot where content from the parent is projected. They solve different problems: grouping, deferred rendering and composition.
Full answer
These three look similar but have different jobs.
ng-container is an invisible wrapper. It lets you apply a structural directive or a binding to several elements without adding an extra div to the page. Typical uses: <ng-container *ngTemplateOutlet="...">, or grouping with a structural directive. Since the new control flow (@if, @for) does not need a host element, you need ng-container less often than before, but it is still useful with ngTemplateOutlet, and to apply a directive to a group.
ng-template defines a template that Angular does not render by itself. It becomes visible only when something creates it: a structural directive (*ngIf is sugar for <ng-template [ngIf]>), ngTemplateOutlet, ViewContainerRef.createEmbeddedView, or a component such as a tab or dialog that receives a TemplateRef. It can take parameters with let- variables: <ng-template let-user="user">. Use it to pass a piece of UI as data, for example to a table that lets you customise a cell.
ng-content is a slot in a component's own template. The parent writes content between the tags (<app-card>Hello</app-card>), and the card shows it where <ng-content /> appears. You can have several slots with select: <ng-content select="[title]" />. The projected content is created by the parent, so its bindings and styles belong to the parent.
Choosing:
Need to group without extra markup: ng-container.
Need to define reusable UI that is rendered later or many times: ng-template.
Need the user of your component to supply markup: ng-content (static) or ng-template passed in (dynamic, with context).
Remember that ng-content projects content that always exists, even if hidden, while content in an ng-template is created only when instantiated.
Angular 20.3, strict template check passes. A Karma test checks the projected title and body, and that the template outlet renders two rows with different context.
Key points
`ng-container` groups with no DOM element.
`ng-template` is not rendered until instantiated. It can take context variables.
`ng-content` is a slot for projected content, with optional `select`.
Use templates when the child must render the content several times or with data.
Common mistakes
Adding extra `div` wrappers when `ng-container` would do.
Expecting content inside an `ng-template` to exist before it is instantiated.
Using `ng-content` when each row needs data from the child, where a template with context is needed.
Follow-ups
How is `*ngIf` related to `ng-template`?
How do you project content into several slots?
What does `ngTemplateOutletContext` do?
Tips
Give one-line jobs: group, define, project.
Mention that `@if` and `@for` reduced the need for `ng-container`.
Show a template with context.
Evaluation rubric
Distinguishes the three correctly.
Gives uses for each.
Understands creation timing and context.
107.angular-0107Easyfresher
How do you add and remove form fields at run time with FormArray in a reactive form?
A FormArray holds an ordered list of controls or groups. Build it with FormBuilder, loop over its controls in the template, add a new group with push, remove with removeAt, and read the whole result from the parent form's value.
Full answer
Use a FormArray when the number of fields is not fixed: phone numbers, subjects with marks, or answers to a quiz.
Set-up:
The parent is a FormGroup that has an array property: subjects: this.fb.array([ this.newSubject() ]).
A small factory returns a group for one row: fb.nonNullable.group({ name: ['', Validators.required], marks: [0, [Validators.min(0), Validators.max(100)]] }).
A getter exposes the array with the right type, for the template and for methods.
The template loops over subjects.controls and uses [formGroupName]="i" for each row, so each row binds to its group.
push adds a row, removeAt(i) removes one, and clear() empties the array.
Reading and validation:
form.value.subjects is an array of plain objects. form.getRawValue() also includes disabled controls.
The array is invalid when any child is invalid, so form.invalid blocks submit.
Add validators on the array itself for rules such as "at least one subject": Validators.minLength(1).
Tips for the template: use track with the control object, not the index. Using the index makes Angular reuse DOM elements wrongly after a removal and can confuse focus. Give remove buttons a label that includes the row number for screen readers.
Typed forms: fb.nonNullable.group and FormArray<FormGroup<...>> give types, so controls[0].controls.marks.value is a number.
Angular 20.3, strict template check passes. A Karma test adds a row, checks that the form is invalid while the new name is empty, then removes the row.
Key points
`FormArray` is a dynamic list of controls or groups.
Add with `push`, remove with `removeAt`, empty with `clear`.
Use `[formGroupName]="i"` per row, and `track` the control object.
Validate the array (`minLength`) and each row.
Common mistakes
Tracking rows by index, which breaks DOM reuse after removal.
Forgetting `formArrayName` or `formGroupName` in the template.
Creating one shared group object and pushing it twice.
Follow-ups
How would you validate that subject names are unique?
What is the difference between `value` and `getRawValue()`?
How would you load existing data into the array?
Tips
Show the row factory. It is the core of the pattern.
Mention `track` by object.
Mention typed forms.
Evaluation rubric
Builds and renders a FormArray correctly.
Adds and removes rows.
Handles validation and typing.
108.angular-0108Easyfresher
What is in angular.json, and how do builders, configurations and projects work in an Angular workspace?
angular.json describes the workspace: each project has architect targets (build, serve, test) that name a builder and its options. Configurations such as production and development override options for a target, and you pick one with --configuration.
Full answer
An Angular workspace is a folder with one or more projects. The file angular.json is the CLI's map of the workspace.
Top level keys:
projects: one entry per application or library. Each has root, sourceRoot, prefix (the component selector prefix, app by default), and architect (the targets).
schematics: defaults for ng generate, for example making components use OnPush, or skipping tests.
cli: workspace settings such as the package manager and analytics.
Inside a project, architect lists targets. A target has a builder and options:
build uses @angular/build:application (esbuild and Vite). Options include browser (the main entry file), tsConfig, assets, styles, polyfills, outputMode and ssr.
serve uses @angular/build:dev-server, and takes a buildTarget from the configuration.
test uses @angular/build:karma (other test builders can be added).
extract-i18n, lint, and others when added.
Configurations are named sets of option overrides. By default production turns on optimisation, hashing and budgets, and development turns off optimisation and enables source maps. defaultConfiguration chooses the one used when you do not pass --configuration. Run ng build --configuration development.
Other files: tsconfig.json (shared compiler options), tsconfig.app.json and tsconfig.spec.json (per target), package.json, and .editorconfig.
You can read and change options with ng config, and many generators edit angular.json for you. Commit this file, and keep changes small and reviewed, because it controls the build.
Angular 20.3. The excerpt follows the structure of the file that Angular CLI 20 generates (builder names and the production and development configurations match the project used for testing here), shortened, with an added staging configuration. It is a data file, not executed.
Key points
`angular.json` lists projects, and each project has targets with a builder and options.
Per-target tsconfig files extend the root `tsconfig.json`.
Common mistakes
Editing production behaviour by changing base options, instead of the production configuration.
Forgetting that `--configuration` affects the target you run.
Not committing `angular.json` changes made by generators.
Follow-ups
How would you add a staging configuration?
What does `ng add` change in this file?
How do multiple projects in one workspace share code?
Tips
Describe the structure: project, target, builder, configuration.
Name the default builder for build and serve.
Mention how to add a configuration.
Evaluation rubric
Explains projects, targets, builders, options and configurations.
Knows the default builder names.
Mentions related tsconfig files.
109.angular-0109Easyfresher
What is the difference between providedIn root and providing a service in a component, and how does that affect how many instances exist?
A service with providedIn root has one shared instance for the whole app. A service listed in a component's providers gets a new instance for each component instance, and its children share it. Use root for shared state and component providers for state that belongs to one component.
Full answer
Dependency injection decides where an instance lives. The providedIn and providers settings choose the scope.
@Injectable({ providedIn: 'root' }) registers the service in the root injector. Angular creates it the first time it is injected, and every part of the app receives the same object. This makes it a singleton, and unused services are removed from the bundle (tree-shakable). It is the default choice for shared data such as the logged in user or a cart.
providers: [CounterService] on a component registers it in that component's element injector. Angular creates a new instance for each instance of the component, and all children of that component see the same one. When the component is destroyed, the service is destroyed too, and its ngOnDestroy runs. This fits state that belongs to one widget, for example the state of one table, or a form wizard, where two copies on the page must not share data.
Other places:
A route's providers array creates an instance that lives as long as that route (an environment injector for the route and its children).
viewProviders is like providers but is not visible to projected content.
A common bug is providing a service in both places by habit: the component then gets its own copy, and shared data seems to "disappear". Another bug is adding a service to the providers of a component that is rendered several times and expecting shared state.
Test question: with providedIn: 'root', two components that inject the service share the same count. With a component-level provider, two instances of the same component show separate counts.
Prefer the narrowest scope that gives the right sharing, and use providedIn: 'root' when you need one shared instance.
typescript
import { Component, Injectable, inject } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class SharedCounter {
count = 0;
}
@Injectable()
export class LocalCounter {
count = 0;
}
@Component({
selector: 'app-counter-box',
providers: [LocalCounter], // new LocalCounter for every <app-counter-box>
template: `
<button (click)="bump()">Bump</button>
local {{ local.count }}, shared {{ shared.count }}
`,
})
export class CounterBoxComponent {
protected readonly local = inject(LocalCounter);
protected readonly shared = inject(SharedCounter);
bump(): void {
this.local.count++;
this.shared.count++;
}
}
@Component({
selector: 'app-two-boxes',
imports: [CounterBoxComponent],
template: `<app-counter-box /><app-counter-box />`,
})
export class TwoBoxesComponent {}
Angular 20.3, strict template check passes. A Karma test shows that two component instances have separate counters while the root service count is shared.
Key points
`providedIn: 'root'` means one shared, tree-shakable instance.
`providers` on a component means one instance per component instance, shared with its children.
Route providers live as long as the route.
Providing in two places creates two instances.
Common mistakes
Adding a root service to component `providers` and losing shared state.
Expecting shared state from a component-level service on a repeated component.
Not realising the instance is destroyed with the component.
Follow-ups
How can you check which instance a component got?
What is the difference between `providers` and `viewProviders`?
When is a route-level provider better than root?
Tips
Use a counter example with two components.
Mention tree-shaking for root services.
Say that you choose the narrowest scope that works.
Evaluation rubric
Explains root and component scope correctly.
Mentions route providers and lifetime.
Recognises the duplicate provider bug.
110.angular-0110Easyfresher
How do you validate two fields together, for example that a password and its confirmation match, in a reactive form?
Put the validator on the parent FormGroup, because a group validator can read all child controls. Return an error object when the values differ, and show the message when the group has the error and the confirmation field has been touched.
Full answer
A control validator only sees its own value. A rule that involves two fields needs a validator at the group level.
Steps:
Write a ValidatorFn that takes an AbstractControl (the group), reads the two child controls, and returns null if the rule passes or an error object such as { passwordMismatch: true } if it fails.
Attach it to the group: fb.group({ ... }, { validators: passwordsMatch }).
In the template, check form.hasError('passwordMismatch'). The error is on the group, not on a control, so confirm.errors does not contain it.
Show the message only after the user has touched the confirmation field: form.hasError('passwordMismatch') && confirm.touched.
Details:
The group validator runs when any child value changes, so it stays in sync when the first password changes later.
Return null when either field is empty, so that required shows its own message and you do not show two messages at once.
To show the error on the confirmation control (for styling), you can set an error with confirm.setErrors(...) inside the validator, but this is fragile. Group-level errors with a computed message are cleaner.
Add aria-describedby linking the confirmation input to the message, and role="alert" on the message.
Other cross-field rules use the same pattern: end date after start date, minimum less than maximum, at least one of several checkboxes checked.
For rules that need the server (is this username free), use an async validator on the control instead.
Angular 20.3, strict template check passes. A Karma test checks the mismatch and match cases through the form.
Key points
Cross-field rules need a validator on the parent group.
Return `null` when valid, or an error object when not.
Read the error with `form.hasError(...)` on the group.
Show messages after touch, and link them with `aria-describedby`.
Common mistakes
Putting the comparison validator on one control, so it misses changes to the other.
Looking for the error in `confirm.errors` when it is on the group.
Showing "required" and "mismatch" at the same time.
Follow-ups
How would you check that an end date is after a start date?
How would you write an async validator for a username?
How do you reuse the validator with different field names?
Tips
Say why the group is the right place.
Return `null` for empty fields.
Mention accessibility of the error message.
Evaluation rubric
Attaches a validator to the group.
Reads the group error correctly.
Handles empty fields and messages.
111.angular-0111Easyfresher
How do you show a loading indicator during navigation using router events?
The Router publishes events such as NavigationStart, NavigationEnd, NavigationCancel and NavigationError. Listen to router.events, set a loading signal to true on start and false on any of the three end events, and show the indicator while it is true.
Full answer
Lazy loaded routes, guards and resolvers take time. Users should see that something is happening.
The Router has an events observable. The main events for one navigation are:
NavigationStart: navigation begins.
RoutesRecognized, GuardsCheckStart, GuardsCheckEnd, ResolveStart, ResolveEnd: the stages in between.
One of three endings: NavigationEnd (success), NavigationCancel (a guard returned false or a newer navigation replaced it) or NavigationError (an error, such as a chunk that failed to load).
To show a spinner:
Filter the events to the four kinds, and map them to a boolean: true for start, false for the three endings.
Convert it to a signal with toSignal(..., { initialValue: false }).
In the template, @if (loading()) { <progress /> }.
Why handle all three endings? If you only hide on NavigationEnd, a cancelled or failed navigation leaves the spinner forever.
Variations:
Add a small delay before showing the indicator (about 150 ms), so fast navigations do not flash.
Use the withNavigationErrorHandler router feature to redirect to an error page.
For a global progress bar, put this logic in one root component, not in each page.
Add aria-busy on the main region and an accessible label on the indicator.
Remember that router.events only emits while someone subscribes, so use it in a component or service created at start-up. In SSR, events also fire on the server.
typescript
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { NavigationCancel, NavigationEnd, NavigationError, NavigationStart, Router, RouterOutlet } from '@angular/router';
import { filter, map } from 'rxjs';
@Component({
selector: 'app-shell',
imports: [RouterOutlet],
template: `
@if (loading()) {
<progress aria-label="Loading page"></progress>
}
<main [attr.aria-busy]="loading()"><router-outlet /></main>
`,
})
export class ShellComponent {
private readonly router = inject(Router);
readonly loading = toSignal(
this.router.events.pipe(
filter(
(e) => e instanceof NavigationStart || e instanceof NavigationEnd || e instanceof NavigationCancel || e instanceof NavigationError,
),
map((e) => e instanceof NavigationStart),
),
{ initialValue: false },
);
}
Angular 20.3, strict template check passes. A Karma test checks that the signal is true during a navigation and false after it ends.
Key points
`router.events` emits navigation events. Start begins, and End, Cancel or Error finish.
Handle all three ending events or the spinner can stay on forever.
`toSignal` gives a simple signal for the template.
Delay showing the indicator to avoid flashes. Add accessible labels.
Common mistakes
Only handling `NavigationEnd`, so cancelled navigations leave the spinner on.
Subscribing in every page component instead of once at the root.
Forgetting to unsubscribe in older code that subscribes manually.
Follow-ups
When is `NavigationCancel` emitted?
How would you delay showing the spinner by 150 ms?
How would you handle a lazy chunk that fails to load?
Tips
List the three endings. It is the usual trap.
Use `toSignal` to show modern style.
Mention accessibility.
Evaluation rubric
Names the navigation events correctly.
Handles all ending events.
Implements the indicator cleanly.
112.angular-0112Easyfresher
What is the difference between hot and cold observables, and how do you turn a cold one into a hot one?
A cold observable starts its work separately for every subscriber, like an HTTP request made again for each subscribe. A hot observable produces values whether or not anyone listens and shares them, like mouse clicks. You make a cold one hot by multicasting with share or shareReplay.
Full answer
An Observable is a description of work. Whether the work is shared depends on where the source is created.
Cold observable: the producer is created when you subscribe. Each subscriber gets its own run. HttpClient.get() is cold: if two places subscribe, two requests are sent. of(1, 2, 3), interval(1000) and from([...]) are also cold. Think of it as a video you press play on for each viewer.
Hot observable: the producer exists outside the subscription, and values are emitted whether or not someone is listening. DOM events, a Subject, and a WebSocket connection that is already open behave this way. A late subscriber misses earlier values. Think of a live TV channel.
Why it matters:
Two async pipes on the same cold observable mean two requests.
A tap side effect runs once per subscriber.
Late subscribers to a hot source may miss values, so you may need a replay.
Making a cold source hot (multicasting):
share(): one shared subscription to the source for all current subscribers. When the last subscriber leaves, the source is unsubscribed, and the next subscriber starts again.
shareReplay({ bufferSize: 1, refCount: true }): also replays the latest value to late subscribers. Use refCount: true so the source stops when nobody listens. Without refCount, the source is never unsubscribed, which can leak.
A Subject or BehaviorSubject that you feed from the source manually.
In signal code, toSignal(source$) subscribes once and shares the latest value with all readers.
Rule: if more than one place needs the same result, share it once.
typescript
import { Observable, share, take, timer } from 'rxjs';
let starts = 0;
const cold$ = new Observable<number>((subscriber) => {
starts++;
subscriber.next(starts);
subscriber.complete();
});
cold$.subscribe();
cold$.subscribe();
console.log('cold, two subscribers, source started', starts, 'times');
let timerStarts = 0;
const timerCold$ = new Observable<number>((subscriber) => {
timerStarts++;
const id = setTimeout(() => {
subscriber.next(1);
subscriber.complete();
}, 10);
return () => clearTimeout(id);
});
const timerShared$ = timerCold$.pipe(share());
let received = 0;
timerShared$.pipe(take(1)).subscribe(() => received++);
timerShared$.pipe(take(1)).subscribe(() => received++);
setTimeout(() => console.log('shared, source started', timerStarts, 'time, subscribers received', received), 40);
RxJS 7.8. The script was run in Node 24 twice with identical output. It counts how many times the cold source starts with and without share.
Key points
Cold: each subscriber triggers its own run (HTTP, `of`, `interval`).
Hot: values are produced independent of subscribers (events, Subjects).
Use `share` or `shareReplay({ bufferSize: 1, refCount: true })` to multicast.
Two subscriptions to a cold HTTP observable send two requests.
Common mistakes
Subscribing twice to an HTTP observable and sending two requests by accident.
Using `shareReplay(1)` without `refCount`, so the source never stops.
Assuming a Subject replays old values to late subscribers.
Follow-ups
What does `refCount` do in `shareReplay`?
Is a `Promise` hot or cold?
How does `toSignal` relate to sharing?
Tips
Use the HTTP example. Everyone knows it.
Name `refCount` and the leak it avoids.
Link to the "two async pipes" bug.
Evaluation rubric
Defines hot and cold correctly with examples.
Explains the practical effects.
Knows how to multicast safely.
113.angular-0113Easyfresher
Which observables do you need to unsubscribe from in Angular, and which clean themselves up?
Observables that complete, such as HttpClient calls, clean up by themselves. Streams that never complete, such as interval, Subjects, form valueChanges, store selections and DOM events, keep running until you unsubscribe. Use the async pipe, toSignal or takeUntilDestroyed so cleanup is automatic.
Full answer
A subscription keeps the callback and everything it references alive. If the source never ends and you never unsubscribe, the component stays in memory after it is destroyed, and the callback keeps running. This is a memory leak.
Clean by themselves (they complete or error):
HttpClient requests: one value then complete.
of, from([...]), timer(1000) (a single timer), take(n) and first() streams.
ActivatedRoute params: Angular destroys them with the route component, so unsubscribing is optional, but harmless.
Need cleanup (they can emit forever):
interval, timer(0, 1000).
Subjects and BehaviorSubjects from services that live longer than the component.
form.valueChanges and statusChanges when the form lives longer than the view.
fromEvent(window, 'resize') and other global events.
Store or WebSocket streams.
router.events (long-lived).
Ways to clean up:
async pipe: subscribes and unsubscribes with the view.
toSignal(obs$): unsubscribes when the injection context is destroyed.
takeUntilDestroyed() (from @angular/core/rxjs-interop) as the last operator of a pipe. Inside the constructor it needs no argument. Outside, pass a DestroyRef.
Subscription fields with unsubscribe() in ngOnDestroy (old style).
take(1) or first() when only one value is needed.
Do not rely on remembering: choose a default (async, toSignal or takeUntilDestroyed) so the safe pattern is also the easy one.
Place takeUntilDestroyed last, so operators after it do not keep the stream alive.
typescript
import { Component, DestroyRef, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-clock',
template: `Ticks: {{ ticks() }}`,
})
export class ClockComponent {
readonly ticks = signal(0);
private readonly destroyRef = inject(DestroyRef);
constructor() {
// In a constructor, takeUntilDestroyed() needs no argument.
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe((n) => this.ticks.set(n + 1));
}
startLater(): void {
// Outside an injection context, pass the DestroyRef.
interval(500)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe();
}
}
RxJS 7.8 and Angular 20.3, type-checked. A Karma test checks that the interval stops ticking after the component is destroyed.
Key points
Completing sources (HTTP, `of`, single `timer`) clean up on their own.
Infinite sources (`interval`, Subjects, events, `valueChanges`) need cleanup.
Prefer `async` pipe, `toSignal` and `takeUntilDestroyed`.
Put `takeUntilDestroyed` last in the pipe.
Common mistakes
Subscribing to a service Subject in `ngOnInit` and never unsubscribing.
Calling `takeUntilDestroyed()` without a `DestroyRef` outside an injection context.
Putting `takeUntilDestroyed` before other operators.
Follow-ups
Why does an HTTP observable not leak?
How does `takeUntilDestroyed` know when to complete?
How do you find leaks with the browser memory profiler?
Tips
Give the two lists clearly: completes and does not complete.
Name the three modern defaults.
Show you know the operator position rule.
Evaluation rubric
Separates self-completing and infinite sources.
Names modern cleanup tools.
Avoids common mistakes.
114.angular-0114Easyfresher
What is the difference between AngularJS and Angular, and why can they not simply be upgraded in place?
AngularJS (version 1.x) was a JavaScript framework built on controllers, scopes and two-way binding, and it reached end of life at the end of 2021. Angular (version 2 and above) is a complete rewrite in TypeScript with components, dependency injection, ahead-of-time compilation and a different change detection model.
Full answer
The name causes confusion. "AngularJS" means version 1.x, released in 2010. "Angular" means version 2 and later, a rewrite released in 2016 and updated twice a year since.
Main differences:
Language: AngularJS used JavaScript (TypeScript was optional and rare). Angular uses TypeScript.
Architecture: AngularJS used controllers, $scope and directives. Angular uses components, services with dependency injection and, in modern versions, standalone components and signals.
Binding and change detection: AngularJS used digest cycles that checked watchers on $scope, with two-way binding everywhere (ng-model). Angular uses one-way data flow by default, zone.js or signals to detect changes, and explicit [(ngModel)] for two-way binding.
Templates: AngularJS parsed templates in the browser at run time (ng-repeat, ng-if). Angular compiles templates ahead of time (AOT) into JavaScript, so apps are smaller and faster, and templates are type-checked.
Mobile and performance: Angular was designed for mobile, lazy loading and tree-shaking.
Tooling: Angular has the CLI, a standard testing setup, and a clear upgrade path with ng update.
Why no in-place upgrade: the programming model changed (scopes versus components, digest versus new change detection, different DI and routing). Migration therefore needs a plan: run both together with ngUpgrade (the @angular/upgrade package) and move one component or service at a time, or rewrite by feature. Today the usual advice is to migrate directly to the current Angular, since AngularJS support ended on 31 December 2021, and it no longer receives fixes from the Angular team.
In interviews, say "Angular" for 2+ and "AngularJS" for 1.x, and mention that all current jobs mean the modern framework.
typescript
import { Component, signal } from '@angular/core';
// AngularJS (1.x): <input ng-model="name"> {{ name }} with controller($scope) { $scope.name = '' }
// Angular (modern): a typed component with a signal and one-way flow by default.
@Component({
selector: 'app-greeting',
template: `
<input [value]="name()" (input)="name.set($any($event.target).value)" />
<p>Hello {{ name() }}</p>
`,
})
export class GreetingComponent {
readonly name = signal('');
}
Conceptual answer. The comparison snippet is the Angular 20 side only, type-checked. The AngularJS side is in comments.
Key points
AngularJS is 1.x (JavaScript, scopes, digest). Angular is 2 and above (TypeScript, components, AOT).
Angular uses one-way flow by default and compiles templates ahead of time.
AngularJS support ended on 31 December 2021.
Migration is gradual with `ngUpgrade` or a feature-by-feature rewrite.
Common mistakes
Using the two names as if they mean the same thing.
Planning an "upgrade" instead of a migration.
Staying on AngularJS without security support.
Follow-ups
How does `ngUpgrade` let both run together?
What replaced `$scope` in Angular?
What would be the first step in migrating a large AngularJS app?
Tips
Clarify the naming at the start.
Give three concrete differences (language, change detection, templates).
State the end of life date (end of 2021).
Evaluation rubric
Distinguishes the two correctly.
Names key technical differences.
Understands migration approach.
115.angular-0115Easyfresher
What is the difference between removing an element with @if and hiding it with the hidden attribute or CSS, and when do you choose each?
@if creates and destroys the element and its component, so its state and subscriptions are reset, while hidden or display none keeps the element alive and only hides it. Use @if when the content is expensive or should reset, and hidden when you toggle often and want to keep state.
Full answer
Both make something disappear from the screen, but they do different work.
@if (show) { <app-chart /> }: when show is false Angular removes the element and destroys any component inside it. Its state, form values, timers and subscriptions are gone. When show becomes true again Angular creates a new instance, and ngOnInit runs again.
[hidden]="!show" or [style.display]="show ? 'block' : 'none'" or a class: the element stays in the DOM and in memory. The component keeps its state and keeps running (timers, subscriptions, change detection). Only the browser hides it.
Choosing:
Use @if when the content is heavy, when it should start fresh each time, or when it must not run in the background.
Use hidden or CSS when you toggle often (tabs that keep their form data), when creation is expensive and you want to keep the result, or when you animate with CSS transitions.
Other points:
The hidden attribute is overridden by CSS such as display: flex. If a style sets display, hidden may not hide the element. Check with a class that sets display: none.
display: none removes the element from the accessibility tree and from the tab order. visibility: hidden hides the element but keeps its space, and opacity: 0 keeps it focusable, which is bad for keyboard users.
With @defer, you can delay creation until a condition or visibility, which helps heavy content.
For tabs with forms, hiding keeps typed values, but removing loses them unless the state lives in a parent or service.
Hidden components still take part in change detection and keep their subscriptions running.
Angular 20.3, strict template check passes. A Karma test shows that the child under @if is destroyed and recreated, while the hidden one is created once.
Key points
`@if` creates and destroys, so state and subscriptions reset.
`hidden` or CSS display keeps the element alive and only hides it.
Choose by cost, state needs, and how often you toggle.
Beware CSS overriding `hidden`, and focusable items hidden only with `opacity`.
Common mistakes
Using `hidden` for heavy components that keep running in the background.
Using `@if` for tab panels and losing form input.
Hiding with `opacity: 0` and leaving the content focusable.
Follow-ups
How would you keep tab form state while using `@if`?
What is the effect on accessibility of `display: none`?
How does `@defer` fit in?
Tips
State the lifecycle difference first.
Give tabs as the example for `hidden`, and heavy charts for `@if`.
Mention focus and accessibility.
Evaluation rubric
Explains creation, destruction and state.
Gives choice criteria.
Mentions CSS and accessibility pitfalls.
116.angular-0116Easyfresher
What is the difference between viewChild, contentChild and their plural forms, and when are the results available?
viewChild queries elements and components in the component's own template, while contentChild queries content that a parent projected between the component's tags. The plural forms return all matches. The signal versions update automatically and are ready after the first render (view) or after content init (content).
Full answer
Queries let a component get references to things in its template or content.
viewChild finds an element, component, or directive declared in the component's own template. Use a template reference name or a class: viewChild('box'), viewChild(ChartComponent). viewChildren returns all matches as a signal of an array.
contentChild finds things that the parent projected into this component through <ng-content>. If a tab group component is used as <app-tabs><app-tab /><app-tab /></app-tabs>, then contentChildren(TabComponent) in the tab group finds the tabs, because they are content, not part of its own view. A viewChild would not find them.
viewChild.required(...) returns Signal<T> and throws if there is no match.
contentChild, contentChildren and viewChildren follow the same pattern.
Because they are signals, they work in computed and effect, and update when @if or @for adds or removes matches.
Options: { read: ElementRef } picks what to return, { descendants: true } includes nested content children.
When are results available? Signal queries return undefined (or an empty array) before the first render, so read them in effect, afterNextRender, or a lifecycle hook after init. Content queries are ready after ngAfterContentInit, and view queries after ngAfterViewInit.
The older decorators (@ViewChild, @ContentChild) still work, but have a static flag and are not reactive. Prefer the signal versions in new code.
A common mistake is using viewChild for projected content, or reading a query in the constructor.
Angular 20.3, strict template check passes. A Karma test checks that the tab group counts the projected tabs and the view query finds its heading.
Key points
`viewChild` is for your own template. `contentChild` is for projected content.
Plural versions return all matches as a signal of an array.
Signal queries are reactive. Use `.required` when a match must exist.
Results are not ready in the constructor. Use hooks, `effect`, or `afterNextRender`.
Common mistakes
Using `viewChild` to find components projected by a parent.
Reading the query in the constructor, where it is still undefined.
Forgetting `descendants: true` for nested content children.
Follow-ups
What does `read` do in a query?
How does `viewChild` behave inside an `@if`?
When would you use `contentChildren` in a component library?
Tips
Give the tab group example for content queries.
Mention signal queries and `.required`.
State when each result is ready.
Evaluation rubric
Distinguishes view and content queries.
Knows signal query APIs and timing.
Avoids the common mistakes.
117.angular-0117Easyfresher
Should you use interfaces or classes for data models in Angular, and what happens to types at run time?
Interfaces exist only at compile time and are erased, so they cost nothing and fit plain JSON from an API. Use a class when you need behaviour, default values or instanceof checks. Types do not validate data at run time, so API responses still need checking.
Full answer
TypeScript types help while you write code, but the browser runs plain JavaScript.
An interface (or type) describes a shape. It produces no JavaScript, so there is no size cost. It matches the plain objects that JSON.parse and HttpClient return: http.get<Student[]>('/api/students'). TypeScript checks the shape in your code, using structural typing: any object with the right properties fits.
A class produces real JavaScript. Use it when you need:
Methods on the data (student.isPassing()).
Default values and a constructor.
instanceof checks, or a class as a dependency injection token.
Private fields.
Important point: http.get<Student[]>() does not create Student objects. The generic only tells the compiler what you expect. If the server sends something else, there is no error at run time, and calling a method that exists only on the class would fail. If you want class instances, map the data: .pipe(map(rows => rows.map(r => new Student(r)))).
Guidance for Angular apps:
Use interfaces or types for API data, and keep them in a models file near the feature.
Use classes for services, components, and rich domain objects.
Use readonly and Readonly<T> for data that should not change, which fits signals and OnPush.
Use union types for fixed sets: type Status = 'pending' | 'live'.
Validate untrusted data at the boundary with a type guard or a schema library when the API is not fully trusted.
Interfaces cannot be used as injection tokens, because they do not exist at run time. Use an InjectionToken or an abstract class.
typescript
interface StudentDto {
name: string;
marks: number;
}
class Student {
readonly name: string;
readonly marks: number;
constructor(name: string, marks: number) {
this.name = name;
this.marks = marks;
}
isPassing(): boolean {
return this.marks >= 40;
}
}
const json = '[{"name":"Asha","marks":82}]';
const dtos = JSON.parse(json) as StudentDto[]; // a type claim, not a conversion
console.log('is a Student?', dtos[0] instanceof Student);
const students = dtos.map((d) => new Student(d.name, d.marks));
console.log('after mapping, passing?', students[0].isPassing());
function isStudentDto(value: unknown): value is StudentDto {
const v = value as Partial<StudentDto> | null;
return typeof v === 'object' && v !== null && typeof v.name === 'string' && typeof v.marks === 'number';
}
console.log('guard accepts bad data?', isStudentDto({ name: 5 }));
TypeScript 5.8, type-checked. The script was run in Node 24 twice with identical output. It shows that parsed JSON is not a class instance until you map it.
Key points
Interfaces are erased at compile time and suit plain JSON.
Use classes for behaviour, defaults, `instanceof`, and DI tokens.
`http.get<T>()` does not create instances or validate data.
Validate untrusted API data at the boundary.
Common mistakes
Expecting `http.get<Student>()` to return a class with methods.
Trying to inject an interface.
Trusting types for data that comes from outside the app.
Follow-ups
How would you convert API JSON to class instances?
What is structural typing?
When would you use a type guard?
Tips
State the erased-at-runtime fact clearly.
Warn about the `http.get<T>` illusion.
Mention `InjectionToken` for interfaces.
Evaluation rubric
Explains compile time versus run time.
Chooses interface or class with reasons.
Knows the generic HTTP limitation.
118.angular-0118Mediummid
What is the difference between ChangeDetectorRef detectChanges, markForCheck, detach and reattach, and when would you use each?
markForCheck marks a component and its ancestors as dirty so the next normal change detection pass checks them, which is the usual fix for OnPush. detectChanges runs change detection for that component and its children right now. detach removes the component from checks until reattach is called.
Full answer
ChangeDetectorRef gives a component control over its own change detection.
markForCheck(): marks this view and all its parents up to the root as "dirty". It does not run anything by itself. The next change detection pass (started by zone.js, an event, or a signal) will check these views, even if they use OnPush. Use it when data changed outside Angular's knowledge for an OnPush component, for example in a callback from a third party library or after a mutation of an input object. It is cheap and safe.
detectChanges(): runs change detection immediately, for this view and its children only (not for parents). Use it when you need the DOM updated now, for example before measuring an element, or in a detached view. Calling it often in loops is expensive. In a view that is already being checked, it can cause confusing errors, so avoid calling it from inside lifecycle hooks of the same view.
detach(): removes the view from the change detection tree. Angular stops checking it on normal passes, so it never updates unless you call detectChanges() yourself. Use it for components with very frequent data (a live chart) where you want to update on your own schedule (for example every 500 ms). reattach() puts it back.
checkNoChanges(): development helper that verifies nothing changed since the last check. It is behind the ExpressionChangedAfterItHasBeenChecked error.
Signals change the picture. When a template reads a signal, Angular marks that view for check automatically when the signal changes, so markForCheck is rarely needed with signals, and OnPush plus signals is the recommended pattern. In zoneless apps, signals, markForCheck, events and async pipe schedule the next pass.
Rule of thumb: prefer signals or the async pipe, use markForCheck for rare outside changes, and use detectChanges and detach only for measured performance work.
typescript
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, inject } from '@angular/core';
@Component({
selector: 'app-live-score',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>Score: {{ score }}</p>`,
})
export class LiveScoreComponent {
private readonly cdr = inject(ChangeDetectorRef);
score = 0;
// A value that changes outside Angular's knowledge, for an OnPush component.
updateFromThirdParty(value: number): void {
this.score = value;
this.cdr.markForCheck();
}
// Take control: stop automatic checks, refresh on your own schedule.
startManual(): void {
this.cdr.detach();
}
refreshNow(value: number): void {
this.score = value;
this.cdr.detectChanges();
}
stopManual(): void {
this.cdr.reattach();
}
}
Angular 20.3, strict template check passes. A Karma test shows that an OnPush view ignores a plain field change, updates after markForCheck, and updates after detach and detectChanges.
Key points
`markForCheck` marks the view and ancestors dirty for the next pass. It is the standard OnPush fix.
`detectChanges` checks this view and its children immediately.
`detach` and `reattach` take a view out of automatic checks, and you control updates.
Signals and the async pipe mark views for you.
Common mistakes
Calling `detectChanges` everywhere to "fix" updates instead of fixing the data flow.
Using `markForCheck` in a loop or every frame.
Detaching a view and forgetting to update it.
Follow-ups
Why does mutating an input object not update an OnPush component?
What does `ExpressionChangedAfterItHasBeenChecked` mean?
How does zoneless change detection decide to run?
Tips
Describe the three in one line each: mark, run now, remove.
Say that `markForCheck` does not run detection.
Mention signals as the modern answer.
Evaluation rubric
Defines each method correctly, including scope.
Gives realistic use cases.
Links to OnPush, signals, and zoneless.
119.angular-0119Mediummid
What happens inside Angular from the moment a user clicks a button until the screen updates, with zone.js and without it?
With zone.js, the browser event runs inside the Angular zone, the handler updates state, and when the zone becomes stable it calls ApplicationRef.tick, which checks the views from the root. Without zone.js, a signal change or markForCheck notifies the scheduler, which runs tick in the next task. Either way, tick refreshes templates and updates the DOM.
Full answer
Walk through it step by step, and give both models.
The user clicks. Angular registered the event listener when it created the view. With zone.js, addEventListener was patched, so the handler runs inside the Angular zone (NgZone).
Angular's listener wrapper runs your handler, for example count.update(...). For OnPush views, the wrapper also marks the view and its ancestors dirty.
Zone.js tracks tasks. When the handler and any microtasks finish and no more are pending, the zone emits onMicrotaskEmpty. NgZone then tells ApplicationRef to run tick().
ApplicationRef.tick() walks the view tree from the root. For each dirty (or default strategy) view it runs the template function in update mode, which compares bound values with the previous ones and updates the DOM only where they differ. It also calls ngDoCheck, content and view hooks, and runs effects and afterRender callbacks. In development mode it then runs a second checkNoChanges pass.
The browser paints.
Without zone.js (zoneless, stable in 20.2): nothing patches events, so Angular needs a notification. Sources are: signals read in a template, markForCheck, the async pipe, ComponentRef.setInput, template event listeners, and attaching views. These call the change detection scheduler, which schedules a tick() in the next macrotask (or animation frame, whichever comes first). The rest of step 4 is identical.
Important consequences:
With zone.js any async work in the zone (timers, promises, XHR) triggers a pass, even if nothing changed. That is simple but can be wasteful.
With signals and zoneless, only views that read a changed signal are refreshed.
A change made outside the zone (runOutsideAngular, or a callback from a library that zone.js did not patch) does not trigger a pass in the zone model.
You can call appRef.tick() yourself, but you rarely should.
typescript
import { ApplicationRef, Component, DoCheck, inject, signal } from '@angular/core';
@Component({
selector: 'app-click-flow',
template: `<button (click)="increment()">Clicked {{ count() }}</button>`,
})
export class ClickFlowComponent implements DoCheck {
private readonly appRef = inject(ApplicationRef);
readonly count = signal(0);
checks = 0;
ngDoCheck(): void {
this.checks++; // runs once per change detection pass of this view
}
increment(): void {
this.count.update((c) => c + 1);
}
forceTick(): void {
this.appRef.tick(); // runs a full pass now. Rarely needed.
}
}
Angular 20.3, type-checked. The component counts its `ngDoCheck` calls. A Karma test checks that a click updates the DOM and increases the count, and calls `ApplicationRef.tick()` once.
Key points
Event listener runs in the Angular zone, handler changes state.
Zone stability triggers `ApplicationRef.tick()`, which refreshes views from the root.
Zoneless: signals, `markForCheck`, events and the async pipe notify a scheduler that runs `tick`.
Template functions update only changed bindings. Dev mode adds a `checkNoChanges` pass.
Common mistakes
Believing Angular re-renders the whole page on every event.
Updating state outside the zone and expecting the screen to change.
Calling `tick()` manually to hide a data-flow problem.
Follow-ups
What does `runOutsideAngular` change in this flow?
Why does a plain object mutation not update an OnPush component?
What is the second `checkNoChanges` pass for?
Tips
Number the steps. It shows you know the pipeline.
Give both models and say what replaces zone.js.
Mention that only changed bindings touch the DOM.
Evaluation rubric
Describes event, handler, tick, template update, and DOM update.
Explains the zoneless alternative correctly.
Understands consequences for performance.
120.angular-0120Mediummid
When and how do you use NgZone.runOutsideAngular, and how do you get back into the zone to update the UI?
Code started inside runOutsideAngular does not trigger change detection when its callbacks run. Use it for high frequency events such as mousemove or scroll and for timers that do not change the UI, then call ngZone.run or update a signal only when the UI must change.
Full answer
With zone.js, every event, timer and promise started inside the Angular zone can trigger a change detection pass when it finishes. For a mousemove listener that fires 60 times a second, that means 60 passes per second even if the template does not change.
NgZone.runOutsideAngular(fn) runs fn in the parent zone. Anything the function starts (event listeners, setInterval, requestAnimationFrame) keeps running in that outer zone, so its callbacks do not notify Angular. Use it when:
Handling high frequency events (scroll, mouse move, resize, drag).
Running animations with requestAnimationFrame.
Starting third party libraries (charts, maps) that attach many listeners and timers.
Running long polling that rarely updates the UI.
To update the UI from outside the zone:
Use a signal. In recent versions, setting a signal that a template reads schedules change detection, even outside the zone (the signal notifies the scheduler). This is the simplest way.
Or call ngZone.run(() => ...), which enters the zone and triggers a pass when it finishes.
Or call ChangeDetectorRef.markForCheck() plus detectChanges() for a specific view.
Cautions:
Zoneless applications (Angular 20.2 and newer) have no NgZone work to do. runOutsideAngular still works and just runs the function, so code that uses it stays valid, but it is no longer a performance tool there.
Do not forget cleanup. Listeners added outside the zone still need to be removed (use DestroyRef).
NgZone.isInAngularZone() helps with debugging.
Measure first. Moving code outside the zone makes data flow harder to follow, so do it only where the profiler shows a cost.
For many apps the better long term answer is signals with zoneless change detection, which avoids the problem.
typescript
import { Component, DestroyRef, ElementRef, NgZone, afterNextRender, inject, signal } from '@angular/core';
@Component({
selector: 'app-pointer-tracker',
template: `
<div #area class="area">Move the mouse here</div>
<p>Last stable position: {{ position() }}</p>
`,
})
export class PointerTrackerComponent {
private readonly zone = inject(NgZone);
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly destroyRef = inject(DestroyRef);
readonly position = signal('none');
insideZoneWhenHandled: boolean | null = null;
constructor() {
afterNextRender(() => {
const area = this.host.nativeElement.querySelector('.area') as HTMLElement;
this.zone.runOutsideAngular(() => {
const onMove = (event: MouseEvent) => {
this.insideZoneWhenHandled = NgZone.isInAngularZone();
// Update the UI only for a meaningful change, not on every move.
if (event.clientX % 50 === 0) {
this.position.set(`${event.clientX},${event.clientY}`);
}
};
area.addEventListener('mousemove', onMove);
this.destroyRef.onDestroy(() => area.removeEventListener('mousemove', onMove));
});
});
}
}
Angular 20.3, strict template check passes. A Karma test checks that the listener runs outside the Angular zone and that the signal value is updated only for the chosen positions.
Key points
`runOutsideAngular` stops zone.js from triggering change detection for the callbacks started inside.
Use it for scroll, mouse move, animation frames and third party libraries.
Return to the UI with a signal update or `ngZone.run`.
Clean up listeners, and measure before using it. In zoneless apps it is not a performance tool.
Common mistakes
Updating a plain property from outside the zone and seeing no UI change.
Forgetting to remove listeners added outside the zone.
Using it everywhere without measuring.
Follow-ups
How does a signal update from outside the zone reach the screen?
How would you test that the handler does not trigger change detection?