Angular Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is Angular?
Correct answer: A full TypeScript framework from Google with components, DI, routing, forms and HTTP out of the box
Angular is an opinionated, batteries-included framework: the router, forms, HTTP client, DI, testing utilities and the CLI are all maintained by the Angular team. React, by contrast, is a rendering library around which you assemble your own stack.
2. Which command creates a new Angular project?
Correct answer:
ng new my-appThe Angular CLI (
npm install -g @angular/cli) scaffolds the project withng new, runs the dev server withng serve, generates code withng generate component nameand builds withng build.3. What does the
@Componentdecorator describe?@Component({ selector: "app-user-card", template: `<h2>{{ name }}</h2>`, styles: `h2 { color: teal; }`, }) export class UserCard { name = "Ann"; }Correct answer: Component metadata: the CSS selector, template and styles of the class
The decorator turns a plain TypeScript class into a component.
selectoris the tag you use in other templates (<app-user-card />),template/templateUrlis the markup,styles/styleUrlare the scoped styles.4. What does
standalonemean for an Angular component?Correct answer: It lists its own dependencies in
importsinstead of an NgModuleStandalone components list the components, directives and pipes they use in
imports. Since Angular 19 components are standalone by default; NgModules are still supported but no longer required.5. How is a standalone Angular application started?
Correct answer:
bootstrapApplication(App, appConfig)inmain.tsbootstrapApplicationrenders the root component and takes anApplicationConfigwithproviderssuch asprovideRouter(routes)andprovideHttpClient().bootstrapModuleis the older NgModule-based way.6. What does the default
ViewEncapsulation.Emulateddo with component styles?Correct answer: Scopes them with generated attributes on its elements and selectors
Angular rewrites selectors like
h2toh2[_ngcontent-abc]so styles do not leak out.ViewEncapsulation.ShadowDomuses native Shadow DOM, andNonemakes the styles global.7. What does
:hostmean in a component's styles?Correct answer: The component's own element (for example
<app-user-card>):host { display: block; }styles the element that matches the selector. By default a custom element isdisplay: inline, so components often set their display mode with:host.8. Which language are Angular applications written in?
Correct answer: TypeScript, which is built into the CLI and compiler
Angular is built with and for TypeScript: decorators, DI by type, and type-checked templates rely on it. The compiler also checks template expressions against component types when
strictTemplatesis enabled.9. What does
{{ user.name }}do in a template?Correct answer: Interpolation: inserts the value as text and keeps it updated
Interpolation renders the expression as text (it is escaped, so it is safe from XSS). For HTML content you would bind
[innerHTML], which Angular sanitizes.10. What is the difference between
src="{{ url }}"and[src]="url"?Correct answer: Both set the
srcproperty, but[src]also keeps non-string values[property]="expr"binds a DOM or component property to an expression of any type, e.g.[disabled]="isSaving". Interpolation in an attribute is shorthand for a string property binding.11. How do you handle a button click?
Correct answer:
<button (click)="save()">Parentheses are event binding. The
$eventvariable gives access to the DOM event:(input)="onInput($event)". Square brackets are for property binding, not events.12. What does
(keyup.enter)="submit()"do?Correct answer: Calls
submit()only when the Enter key is releasedAngular supports key event filters:
keydown.escape,keyup.shift.aand so on. This avoids checkingevent.keymanually inside the handler.13. What is the "banana in a box" syntax
[(ngModel)]="name"?Correct answer: Two-way binding: a property binding plus an event binding
[(x)]is sugar for[x]="value" (xChange)="value = $event".ngModelcomes fromFormsModule, which must be added to the component'simports.14. How do you toggle a CSS class depending on a condition?
Correct answer:
[class.active]="isActive"Class binding adds or removes one class. For several classes there is
[class]="{ active: isActive, disabled: isDisabled }", and for styles[style.width.px]="width".15. What is a template reference variable
#nameInput?<input #nameInput /> <button (click)="greet(nameInput.value)">Greet</button>Correct answer: A reference to the element or component, usable elsewhere in the template
#refon a DOM element points to that element; on a component it points to the component instance. The variable is available in the template only; in the class you useviewChild()to get a reference.16. Why should template expressions be simple and free of side effects?
Correct answer: They re-run on every change detection, so heavy logic slows the app
Calling
getTotal()in a template runs it during every check. Prefer fields,computed()signals or pure pipes for derived values, and keep logic in the class.17. Which Angular feature makes
{{ user?.address?.city }}safe whenuserisnull?Correct answer: Optional chaining
?.in template expressionsTemplates support optional chaining and nullish coalescing (
??) like TypeScript. WithstrictTemplatesthe compiler also warns when you access a property of a possibly null value.18. How do you conditionally render a block in modern Angular templates?
@if (user) { <p>Hello, {{ user.name }}</p> } @else { <p>Please sign in</p> }Correct answer: With the built-in
@if/@elseblock shown aboveBuilt-in control flow (
@if,@for,@switch) has been stable since Angular 17. It needs no imports and is faster than the older*ngIf/*ngForstructural directives.19. What is required in an
@forblock?@for (item of items; track item.id) { <li>{{ item.name }}</li> }Correct answer: A
trackexpression that identifies each itemtracktells Angular how to match items between renders so it can reuse DOM nodes instead of recreating them. Use a stable id;track $indexis acceptable only for static lists.20. What does the
@emptyblock do?@for (todo of todos; track todo.id) { <li>{{ todo.title }}</li> } @empty { <li>No tasks yet</li> }Correct answer: Renders its content when the collection is empty
@emptyreplaces the common@if (todos.length === 0)check. Inside@foryou can also use$index,$first,$last,$even,$oddand$count.21. Which block selects one of several templates by value?
Correct answer:
@switchwith@caseand@default@switch (status) { @case ('loading') {...} @case ('error') {...} @default {...} }. Cases are compared with===, and there is no fall-through between them.22. What are pipes in Angular templates?
<p>{{ price | currency: 'EUR' }}</p> <p>{{ createdAt | date: 'short' }}</p>Correct answer: Functions that format a value for display, used with
|Built-in pipes include
date,currency,number,percent,uppercase,jsonandasync. You can chain them and pass arguments after a colon.23. What does the
asyncpipe do?@if (user$ | async; as user) { <p>{{ user.name }}</p> }Correct answer: Subscribes to a stream, returns its latest value, unsubscribes on destroy
The
asyncpipe manages the subscription for you, so there is no manualsubscribe/unsubscribeand no memory leak. It also marks the component for check when a new value arrives.24. How do you create a custom pipe?
Correct answer: A class with
@Pipe({ name: 'truncate' })and atransform()methodAdd the pipe class to the
importsof the component that uses it. Pipes are pure by default:transformruns again only when the input value or arguments change by reference.25. How does a child component receive data from its parent?
export class UserCard { name = input.required<string>(); } // parent: <app-user-card [name]="user.name" />Correct answer: Through
input(), bound with[name]in the parentinput()returns a read-only signal, so in the template you read it asname().input.required()makes the binding mandatory. The older equivalent is the@Input()decorator.26. How does a child component notify its parent about an event?
export class Counter { changed = output<number>(); inc() { this.changed.emit(1); } } // parent: <app-counter (changed)="onChanged($event)" />Correct answer: With
output()and a call to.emit(value)The parent listens with event binding, and
$eventcontains the emitted value. The older equivalent is@Output() changed = new EventEmitter<number>().27. Why can't a child change the value of a signal created by
input()?Correct answer: Inputs are read-only: the parent owns the value
One-way data flow keeps the ownership clear. If the child needs to change it, emit an output, or use
model(), which creates a two-way bindable signal:<app-rating [(value)]="rating" />.28. What is
<ng-content />used for?<!-- card.html --> <div class="card"><ng-content /></div> <!-- usage --> <app-card><p>Any content</p></app-card>Correct answer: Content projection: it renders what the parent puts between the tags
It is the Angular equivalent of
childrenin React or slots in Vue. Several slots can be selected with<ng-content select="[card-title]" />.29. What is a service in Angular?
@Injectable({ providedIn: "root" }) export class CartService { items = signal<Item[]>([]); }Correct answer: A class with shared logic that Angular creates and injects
Services hold business logic, API calls and shared state, keeping components thin.
providedIn: 'root'registers one app-wide instance that is tree-shaken away if no one uses it.30. How do you get a service instance inside a component?
Correct answer:
private cart = inject(CartService);(or a constructor parameter)Dependency injection supplies the instance, so all components share one object and tests can replace it with a fake.
newcreates an unrelated copy and hard-wires the dependency.31. Where can
inject()be called?Correct answer: In an injection context, such as field initializers or the constructor
Calling
inject()in an event handler throwsNG0203. Inject dependencies once at construction and use them later in methods.32. What does
providedIn: 'root'mean?Correct answer: One shared instance for the whole app, created on first injection
Root services are singletons. If a component lists the service in its own
providers, it gets a separate instance for itself and its children.33. Why is dependency injection useful for testing?
Correct answer: Tests can swap in a fake service without changing the component
TestBed.configureTestingModule({ providers: [{ provide: ApiService, useValue: fakeApi }] })swaps the real service for a stub. Components only depend on what they inject.34. What is
ngOnInittypically used for?Correct answer: Setup that needs the inputs, such as loading data
Inputs are already set when
ngOnInitruns, but not yet in the constructor. The constructor is for injecting dependencies; heavier work belongs inngOnInit.35. When is
ngOnDestroycalled?Correct answer: Right before Angular removes the component from the view
Use it (or
DestroyRef.onDestroy) to stop timers, unsubscribe from long-lived Observables and detach listeners. Otherwise they keep running and leak memory.36. When does
ngOnChangesrun?Correct answer: When an input changes, starting before
ngOnInitIt receives a
SimpleChangesobject with the previous and current values. With signal inputs you usually don't need it:computed()oreffect()react to input changes directly.37. What is a signal in Angular?
count = signal(0); increment() { this.count.update((c) => c + 1); } // template: {{ count() }}Correct answer: A reactive value wrapper that Angular tracks when you read
count()Writable signals are changed with
set(value)orupdate(fn). Angular knows which templates read a signal and refreshes them precisely when it changes.38. What is
computed()used for?firstName = signal("Ann"); lastName = signal("Lee"); fullName = computed(() => `${this.firstName()} ${this.lastName()}`);Correct answer: A read-only signal derived from other signals
computedis lazy and memoized: it recalculates only when a dependency changes and someone reads it. You can'tseta computed signal.39. Why is it wrong to mutate an array inside a signal like this?
items = signal<string[]>([]); add(x: string) { this.items().push(x); }Correct answer: The reference stays the same, so Angular isn't notified
Signals compare values with
Object.isby default. Mutating the same array keeps the reference, so dependents are not notified. Create a new array or object instead.40. What does
effect()do?Correct answer: Runs a function whenever the signals it reads change
Effects run at least once and then whenever their dependencies change. They are for side effects; derived values should use
computed().41. How are routes configured in an Angular app?
export const routes: Routes = [ { path: "", component: Home }, { path: "users/:id", component: UserPage }, { path: "**", component: NotFound }, ];Correct answer: With a
Routesarray passed toprovideRouter(routes)The router matches the URL against paths in order.
:idis a route parameter,**is a wildcard for unknown URLs and should go last.42. Where does the router render the matched component?
Correct answer: In
<router-outlet />RouterOutletis a placeholder in a layout component. Nested routes (children) render in an outlet inside the parent route's component.43. How do you create a navigation link without a full page reload?
Correct answer:
<a routerLink="/users">Users</a>routerLinknavigates on the client.routerLinkActive="active"adds a class when the link matches the current URL. A plainhrefreloads the whole application.44. How do you navigate from code, for example after saving a form?
Correct answer:
inject(Router).navigate(['/users', id])Router.navigatetakes an array of segments;navigateByUrltakes a string. Both keep the application state, unlike changinglocation.href.45. What are the two classic approaches to forms in Angular?
Correct answer: Template-driven (
ngModel) and reactive (FormGroup) formsTemplate-driven forms are quick for simple cases; the model lives in the template. Reactive forms define the model in the class, are explicit, typed and easier to test.
46. How do you connect a reactive form to the template?
form = new FormGroup({ email: new FormControl("", { nonNullable: true, validators: [Validators.required, Validators.email] }), });Correct answer:
[formGroup]="form"on the form,formControlNameon each inputDirectives from
ReactiveFormsModulelink the DOM to the controls. The value is inform.value(orgetRawValue()) and the validity inform.valid.47. How do you show a validation error only after the user has touched the field?
Correct answer: Check
control.invalid && control.touched(ordirty) before showing the messageControls track
touched(blurred),dirty(changed) anderrors(e.g.{ required: true }). Showing errors right away on an untouched field is annoying for users.48. How do you make an HTTP GET request in Angular?
private http = inject(HttpClient); getUsers() { return this.http.get<User[]>("/api/users"); }Correct answer: With
HttpClient, which returns an Observable; the request is sent onsubscribeRegister the client with
provideHttpClient(). HTTP Observables are cold: nothing happens until something subscribes (manually or via theasyncpipe), and each subscription sends a new request.49. What is an Observable (RxJS)?
Correct answer: A lazy stream that can emit many values over time
A Promise resolves once and starts immediately; an Observable starts on subscription, can emit zero or many values and can be cancelled with
unsubscribe().50. What does
pipe(map(...), filter(...))do on an Observable?Correct answer: Chains operators that transform the stream into a new Observable
Operators are pure functions:
users$.pipe(map((list) => list.filter((u) => u.active)))returns a new Observable without changing the source and without subscribing.51. Which command starts the local development server?
Correct answer:
ng serveng servebuilds the app in memory, serves it (by default on port 4200) and reloads the page when files change.ng buildproduces files for deployment.52. What does
ng generate component user-carddo?Correct answer: Creates the class, template, styles and test files
ng generate(orng g) also creates services, pipes, directives, guards and more, following the project's conventions.53. How do you declare an input that the parent must always provide?
export class UserCard { user = input.required<User>(); }Correct answer: With
input.required<T>(), checked by the compilerA required input has no default value, so its type doesn't include
undefined. Read it in the template or class as a signal:user().54. What does
<ng-container>render in the DOM?Correct answer: Nothing: it only groups content in the template
It's handy when a wrapper element would break layout (e.g. inside a
<ul>or a flex container) or to host a structural directive.55. Which variables are available inside an
@forblock?@for (item of items; track item.id; let i = $index, last = $last) { <li>{{ i + 1 }}. {{ item.name }} @if (!last) { , }</li> }Correct answer:
$index,$first,$last,$even,$odd,$countThey can be used directly or aliased with
let. Aliases help in nested loops where the inner$indexwould shadow the outer one.56. How do you set an inline style with a unit, e.g. width in pixels?
<div [style.width.px]="size"></div>Correct answer: Bind
[style.width.px], and Angular adds the unitStyle bindings support units like
.px,.%and.em. Anullvalue removes the style.57. How do you highlight the menu link for the current route?
<a routerLink="/users" routerLinkActive="active">Users</a>Correct answer: Add
routerLinkActivewith the CSS class to applyThe directive adds the class while the link's route is active.
[routerLinkActiveOptions]="{ exact: true }"prevents/from matching every page.58. How do you show a "Page not found" component for unknown URLs?
{ path: '**', component: NotFound }Correct answer: Add a wildcard route
**at the end of the routesThe router uses the first matching route, so the wildcard must be last, otherwise it would catch every URL.
59. How do you read the
:idparameter of the current route in a component?private route = inject(ActivatedRoute); id = this.route.snapshot.paramMap.get('id');Correct answer: Inject
ActivatedRouteand read itsparamMapThe snapshot is enough if the component is recreated per id. If the same component stays on screen while the id changes, subscribe to
paramMapor use input binding.60. How do you set the browser tab title for a route?
{ path: 'settings', component: Settings, title: 'Settings' }Correct answer: Use the
titleproperty of the routeThe router updates the title on navigation. A custom
TitleStrategycan add a suffix like " | My App" to every page.61. Why doesn't
this.http.get('/api/users')send any request?Correct answer: HTTP Observables are cold: the request starts on subscribe
Each subscription sends a new request. That's why two
asyncpipes on the same Observable can trigger two calls.62. What must be registered to inject
HttpClientin a standalone app?bootstrapApplication(App, { providers: [provideHttpClient()], });Correct answer:
provideHttpClient()in the application providersFeatures like interceptors or the
fetchbackend are added as arguments:provideHttpClient(withInterceptors([...]), withFetch()).63. How do you format a date in a template?
{{ order.createdAt | date: 'dd.MM.yyyy' }}Correct answer: With the built-in
datepipe and a formatBuilt-in pipes like
date,currency,numberandpercentuse the app's locale. Pipes are imported into standalone components (e.g.DatePipe).64. What is
@letused for in a template?@let total = price() * quantity(); <p>Total: {{ total }}</p>Correct answer: Declaring a local read-only variable in the template
@letavoids repeating long expressions or severalasyncpipes. The value is recalculated whenever the template is checked.65. Where do you keep different API URLs for development and production builds?
Correct answer: In environment files swapped at build time
Anything in the frontend bundle is public, so environment files must contain only non-secret settings like API base URLs.
66. How do you emit a value from a component declared with
output()?saved = output<User>(); save() { this.saved.emit(this.user()); }Correct answer: Call
.emit(value)on the outputThe parent listens with
(saved)="onSaved($event)", where$eventis the emitted value.67. Why should a template call
user()rather thanuserwhenuseris a signal?Correct answer: A signal is a getter: the call reads it and tracks it
Without the call, the template would show the function itself. Reading signals in templates is what lets Angular update only affected views.
68. How do you update a signal based on its current value?
count = signal(0); increment() { this.count.update((c) => c + 1); }Correct answer: With
update(fn), given the current valueset(value)replaces the value;update(fn)derives the new one from the old. Both notify everything that reads the signal.69. What does
[disabled]="form.invalid"on a submit button do?Correct answer: Binds the button's
disabledstate to form validityProperty binding keeps the DOM in sync with component state. Showing why the form is invalid is still important for usability.
70. Which validators make a field mandatory and check an email format?
email = new FormControl('', [Validators.required, Validators.email]);Correct answer:
Validators.requiredandValidators.emailBuilt-in validators also include
minLength,maxLength,min,maxandpattern. Errors are available incontrol.errors.71. What does
ng buildproduce by default in a new project?Correct answer: An optimized production build in the
dist/folderThe production configuration minifies code, removes unused code and adds hashes to file names for caching.
72. Which file is the entry point that bootstraps a standalone Angular app?
Correct answer:
main.tsmain.tscallsbootstrapApplicationwith the root component and app config.index.htmlcontains the root element where the app is rendered.73. What does
RouterLinkwith an array do?<a [routerLink]="['/users', user.id]">Open</a>Correct answer: Builds the URL
/users/<id>from segmentsSegments are encoded correctly. Query parameters are passed separately with
[queryParams].74. How do you show a button only to admins and a label to everyone else?
@if (user().isAdmin) { <button>Delete</button> } @else { <span>Read only</span> }Correct answer: With
@if/@elseblocks@ifremoves the elements from the DOM. Hiding UI is not security - the server must also check permissions.75. What is TypeScript strict mode in an Angular project useful for?
Correct answer: Catching more errors at compile time, templates included
New projects enable
strictandstrictTemplatesby default, so wrong bindings and possiblenullvalues are reported during the build.