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. 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. 2. Which command creates a new Angular project?

    Correct answer: ng new my-app

    The Angular CLI (npm install -g @angular/cli) scaffolds the project with ng new, runs the dev server with ng serve, generates code with ng generate component name and builds with ng build.

  3. 3. What does the @Component decorator 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. selector is the tag you use in other templates (<app-user-card />), template/templateUrl is the markup, styles/styleUrl are the scoped styles.

  4. 4. What does standalone mean for an Angular component?

    Correct answer: It lists its own dependencies in imports instead of an NgModule

    Standalone 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. 5. How is a standalone Angular application started?

    Correct answer: bootstrapApplication(App, appConfig) in main.ts

    bootstrapApplication renders the root component and takes an ApplicationConfig with providers such as provideRouter(routes) and provideHttpClient(). bootstrapModule is the older NgModule-based way.

  6. 6. What does the default ViewEncapsulation.Emulated do with component styles?

    Correct answer: Scopes them with generated attributes on its elements and selectors

    Angular rewrites selectors like h2 to h2[_ngcontent-abc] so styles do not leak out. ViewEncapsulation.ShadowDom uses native Shadow DOM, and None makes the styles global.

  7. 7. What does :host mean 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 is display: inline, so components often set their display mode with :host.

  8. 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 strictTemplates is enabled.

  9. 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. 10. What is the difference between src="{{ url }}" and [src]="url"?

    Correct answer: Both set the src property, 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. 11. How do you handle a button click?

    Correct answer: <button (click)="save()">

    Parentheses are event binding. The $event variable gives access to the DOM event: (input)="onInput($event)". Square brackets are for property binding, not events.

  12. 12. What does (keyup.enter)="submit()" do?

    Correct answer: Calls submit() only when the Enter key is released

    Angular supports key event filters: keydown.escape, keyup.shift.a and so on. This avoids checking event.key manually inside the handler.

  13. 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". ngModel comes from FormsModule, which must be added to the component's imports.

  14. 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. 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

    #ref on 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 use viewChild() to get a reference.

  16. 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. 17. Which Angular feature makes {{ user?.address?.city }} safe when user is null?

    Correct answer: Optional chaining ?. in template expressions

    Templates support optional chaining and nullish coalescing (??) like TypeScript. With strictTemplates the compiler also warns when you access a property of a possibly null value.

  18. 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 / @else block shown above

    Built-in control flow (@if, @for, @switch) has been stable since Angular 17. It needs no imports and is faster than the older *ngIf/*ngFor structural directives.

  19. 19. What is required in an @for block?

    @for (item of items; track item.id) {
      <li>{{ item.name }}</li>
    }

    Correct answer: A track expression that identifies each item

    track tells Angular how to match items between renders so it can reuse DOM nodes instead of recreating them. Use a stable id; track $index is acceptable only for static lists.

  20. 20. What does the @empty block 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

    @empty replaces the common @if (todos.length === 0) check. Inside @for you can also use $index, $first, $last, $even, $odd and $count.

  21. 21. Which block selects one of several templates by value?

    Correct answer: @switch with @case and @default

    @switch (status) { @case ('loading') {...} @case ('error') {...} @default {...} }. Cases are compared with ===, and there is no fall-through between them.

  22. 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, json and async. You can chain them and pass arguments after a colon.

  23. 23. What does the async pipe do?

    @if (user$ | async; as user) {
      <p>{{ user.name }}</p>
    }

    Correct answer: Subscribes to a stream, returns its latest value, unsubscribes on destroy

    The async pipe manages the subscription for you, so there is no manual subscribe/unsubscribe and no memory leak. It also marks the component for check when a new value arrives.

  24. 24. How do you create a custom pipe?

    Correct answer: A class with @Pipe({ name: 'truncate' }) and a transform() method

    Add the pipe class to the imports of the component that uses it. Pipes are pure by default: transform runs again only when the input value or arguments change by reference.

  25. 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 parent

    input() returns a read-only signal, so in the template you read it as name(). input.required() makes the binding mandatory. The older equivalent is the @Input() decorator.

  26. 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 $event contains the emitted value. The older equivalent is @Output() changed = new EventEmitter<number>().

  27. 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. 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 children in React or slots in Vue. Several slots can be selected with <ng-content select="[card-title]" />.

  29. 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. 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. new creates an unrelated copy and hard-wires the dependency.

  31. 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 throws NG0203. Inject dependencies once at construction and use them later in methods.

  32. 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. 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. 34. What is ngOnInit typically used for?

    Correct answer: Setup that needs the inputs, such as loading data

    Inputs are already set when ngOnInit runs, but not yet in the constructor. The constructor is for injecting dependencies; heavier work belongs in ngOnInit.

  35. 35. When is ngOnDestroy called?

    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. 36. When does ngOnChanges run?

    Correct answer: When an input changes, starting before ngOnInit

    It receives a SimpleChanges object with the previous and current values. With signal inputs you usually don't need it: computed() or effect() react to input changes directly.

  37. 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) or update(fn). Angular knows which templates read a signal and refreshes them precisely when it changes.

  38. 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

    computed is lazy and memoized: it recalculates only when a dependency changes and someone reads it. You can't set a computed signal.

  39. 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.is by default. Mutating the same array keeps the reference, so dependents are not notified. Create a new array or object instead.

  40. 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. 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 Routes array passed to provideRouter(routes)

    The router matches the URL against paths in order. :id is a route parameter, ** is a wildcard for unknown URLs and should go last.

  42. 42. Where does the router render the matched component?

    Correct answer: In <router-outlet />

    RouterOutlet is a placeholder in a layout component. Nested routes (children) render in an outlet inside the parent route's component.

  43. 43. How do you create a navigation link without a full page reload?

    Correct answer: <a routerLink="/users">Users</a>

    routerLink navigates on the client. routerLinkActive="active" adds a class when the link matches the current URL. A plain href reloads the whole application.

  44. 44. How do you navigate from code, for example after saving a form?

    Correct answer: inject(Router).navigate(['/users', id])

    Router.navigate takes an array of segments; navigateByUrl takes a string. Both keep the application state, unlike changing location.href.

  45. 45. What are the two classic approaches to forms in Angular?

    Correct answer: Template-driven (ngModel) and reactive (FormGroup) forms

    Template-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. 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, formControlName on each input

    Directives from ReactiveFormsModule link the DOM to the controls. The value is in form.value (or getRawValue()) and the validity in form.valid.

  47. 47. How do you show a validation error only after the user has touched the field?

    Correct answer: Check control.invalid && control.touched (or dirty) before showing the message

    Controls track touched (blurred), dirty (changed) and errors (e.g. { required: true }). Showing errors right away on an untouched field is annoying for users.

  48. 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 on subscribe

    Register the client with provideHttpClient(). HTTP Observables are cold: nothing happens until something subscribes (manually or via the async pipe), and each subscription sends a new request.

  49. 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. 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. 51. Which command starts the local development server?

    Correct answer: ng serve

    ng serve builds the app in memory, serves it (by default on port 4200) and reloads the page when files change. ng build produces files for deployment.

  52. 52. What does ng generate component user-card do?

    Correct answer: Creates the class, template, styles and test files

    ng generate (or ng g) also creates services, pipes, directives, guards and more, following the project's conventions.

  53. 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 compiler

    A 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. 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. 55. Which variables are available inside an @for block?

    @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, $count

    They can be used directly or aliased with let. Aliases help in nested loops where the inner $index would shadow the outer one.

  56. 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 unit

    Style bindings support units like .px, .% and .em. A null value removes the style.

  57. 57. How do you highlight the menu link for the current route?

    <a routerLink="/users" routerLinkActive="active">Users</a>

    Correct answer: Add routerLinkActive with the CSS class to apply

    The directive adds the class while the link's route is active. [routerLinkActiveOptions]="{ exact: true }" prevents / from matching every page.

  58. 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 routes

    The router uses the first matching route, so the wildcard must be last, otherwise it would catch every URL.

  59. 59. How do you read the :id parameter of the current route in a component?

    private route = inject(ActivatedRoute);
    id = this.route.snapshot.paramMap.get('id');

    Correct answer: Inject ActivatedRoute and read its paramMap

    The snapshot is enough if the component is recreated per id. If the same component stays on screen while the id changes, subscribe to paramMap or use input binding.

  60. 60. How do you set the browser tab title for a route?

    { path: 'settings', component: Settings, title: 'Settings' }

    Correct answer: Use the title property of the route

    The router updates the title on navigation. A custom TitleStrategy can add a suffix like " | My App" to every page.

  61. 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 async pipes on the same Observable can trigger two calls.

  62. 62. What must be registered to inject HttpClient in a standalone app?

    bootstrapApplication(App, {
      providers: [provideHttpClient()],
    });

    Correct answer: provideHttpClient() in the application providers

    Features like interceptors or the fetch backend are added as arguments: provideHttpClient(withInterceptors([...]), withFetch()).

  63. 63. How do you format a date in a template?

    {{ order.createdAt | date: 'dd.MM.yyyy' }}

    Correct answer: With the built-in date pipe and a format

    Built-in pipes like date, currency, number and percent use the app's locale. Pipes are imported into standalone components (e.g. DatePipe).

  64. 64. What is @let used for in a template?

    @let total = price() * quantity();
    <p>Total: {{ total }}</p>

    Correct answer: Declaring a local read-only variable in the template

    @let avoids repeating long expressions or several async pipes. The value is recalculated whenever the template is checked.

  65. 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. 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 output

    The parent listens with (saved)="onSaved($event)", where $event is the emitted value.

  67. 67. Why should a template call user() rather than user when user is 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. 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 value

    set(value) replaces the value; update(fn) derives the new one from the old. Both notify everything that reads the signal.

  69. 69. What does [disabled]="form.invalid" on a submit button do?

    Correct answer: Binds the button's disabled state to form validity

    Property binding keeps the DOM in sync with component state. Showing why the form is invalid is still important for usability.

  70. 70. Which validators make a field mandatory and check an email format?

    email = new FormControl('', [Validators.required, Validators.email]);

    Correct answer: Validators.required and Validators.email

    Built-in validators also include minLength, maxLength, min, max and pattern. Errors are available in control.errors.

  71. 71. What does ng build produce by default in a new project?

    Correct answer: An optimized production build in the dist/ folder

    The production configuration minifies code, removes unused code and adds hashes to file names for caching.

  72. 72. Which file is the entry point that bootstraps a standalone Angular app?

    Correct answer: main.ts

    main.ts calls bootstrapApplication with the root component and app config. index.html contains the root element where the app is rendered.

  73. 73. What does RouterLink with an array do?

    <a [routerLink]="['/users', user.id]">Open</a>

    Correct answer: Builds the URL /users/<id> from segments

    Segments are encoded correctly. Query parameters are passed separately with [queryParams].

  74. 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 / @else blocks

    @if removes the elements from the DOM. Hiding UI is not security - the server must also check permissions.

  75. 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 strict and strictTemplates by default, so wrong bindings and possible null values are reported during the build.