Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Short answer: Change Detection Strategy Description When to Use Default Angular checks every component in the component tree every cycle Simple apps or components with frequent changes OnPush Angular checks component onl…
Short answer: ✅ Example code <form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)"> <input name="username" ngModel required minlength="4" /> <button type="submit…
Short answer: pplies CSS class when link's route is ctive ✅ Example: <a routerLink="/home" routerLinkActive="active-link">Home</a> ctive-link is applied when the current route is /home. Ex…
Short answer: @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } } Example code @Directive({ selector: '[appHig…
Short answer: An Angular application mainly consists of: Modules (NgModules) – containers for a cohesive block of code Components – control views (HTML + logic) Templates – HTML with Angular syntax Services – for busines…
Short answer: Commonly done using: Login forms that send credentials to backend. Receive a token (usually JWT) to identify the user. Use Angular guards (like canActivate) to protect routes based on user roles. Store toke…
Short answer: Common techniques: Use OnPush change detection. Implement trackBy in *ngFor. Use lazy loading for modules. Avoid heavy computations in templates. Use pure pipes for filtering/formatting. Use memoization to…
Short answer: ✅ Example code // app-routing.module.ts const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes…
Short answer: These are attribute directives used to dynamically set styles or CSS classes. Explain a bit more ➤ ngClass: Apply CSS classes <div [ngClass]="{'active': isActive, 'disabled': !isActive}"><…
Short answer: Can you give examples? Directives are instructions in the DOM. They help Angular extend HTML's capabilities. Types of Directives: Real-world example (ShopNest) A shared CartService is injected into header a…
Short answer: Break down large components: Divide UI into smaller, reusable child components. Explain a bit more Use container/presentation pattern: Container components handle logic and data fetching. Presentation compo…
Short answer: The Angular compiler converts Angular templates and TypeScript code into efficient JavaScript code. There are two modes: JIT (Just-in-Time): Compilation happens in the browser at runtime. AOT (Ahead-of-Time…
Short answer: uthorization in Angular? Commonly done using: Login forms that send credentials to backend. Receive a token (usually JWT) to identify the user. Use Angular guards (like canActivate) to protect routes based…
Short answer: TestBed is the primary API to configure and initialize the environment for unit testing Angular components and services. It allows you to declare components, provide services, import modules, and compile te…
Short answer: Use npm or yarn to install the package: npm install lodash If the library requires it, add typings: npm install --save-dev @types/lodash Some libraries have Angular-specific schematics that you can add via:…
Short answer: To use a module’s components/directives/pipes, import it in your module’s imports array. To make components/directives/pipes available to other modules, export them in your module’s exports array. Example c…
Short answer: Applications? Common techniques: Use OnPush change detection. Implement trackBy in *ngFor. Use lazy loading for modules. Avoid heavy computations in templates. Use pure pipes for filtering/formatting. Use m…
Short answer: ✅ Example code this.profileForm = new FormGroup({ firstName: new FormControl('', Validators.required), lastName: new FormControl(''), email: new FormControl('', [Validators.required, Validators.email]) });…
Short answer: Use built-in validators via HTML attributes like required, minlength. Use Angular directives like #username="ngModel" to check validity. ✅ Example code <input name="email" ngModel req…
Short answer: And configuration to manage navigation between views. Explain a bit more ✅ Imports in App: import { RouterModule } from '@angular/router'; You use it with RouterModule.forRoot() (for root module) or RouterM…
Short answer: Examples: <!-- *ngIf --> <div *ngIf="user.isLoggedIn">Welcome, {{ user.name }}</div> <!-- *ngFor --> <li *ngFor="let item of items">{{ item }}</li> Re…
Short answer: Directives are instructions in the DOM. They help Angular extend HTML's capabilities. Types of Directives: Real-world example (ShopNest) A shared CartService is injected into header and product pages so bot…
Short answer: XSS (Cross-Site Scripting) Protection: Angular automatically sanitizes dangerous content in templates (e.g., {{ userInput }}). Explain a bit more Use DomSanitizer for trusted content. Binding syntax prevent…
Short answer: Provide a mock implementation of the service in TestBed using the providers array. Use useClass, useValue, or useFactory to inject mocks. Example code class MockDataService { getData() { return of(['mock da…
Short answer: trackBy is a function used with *ngFor to tell Angular how to track list items uniquely. Why it matters: Without trackBy, Angular recreates DOM elements on each update, causing performance overhead. ✅ Examp…
Angular Angular Tutorial · Angular
Short answer: Change Detection Strategy Description When to Use Default Angular checks every component in the component tree every cycle Simple apps or components with frequent changes OnPush Angular checks component only if input references change or events Optimizes performance, suitable for immutable data & smart components How to set OnPush: @Component({ selector: 'app-example', changeDetection:…
ChangeDetectionStrategy.OnPush, template: `...` }) export class ExampleComponent {} Key Difference: Default: Runs change detection every time. OnPush: Runs only when inputs change by reference or manual trigger.
A shared CartService is injected into header and product pages so both see the same cart count.
Angular Angular Tutorial · Angular
Short answer: ✅
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)"> <input name="username" ngModel required minlength="4" /> <button type="submit">Submit</button> </form> onSubmit(form: NgForm) { console.log(form.value); }
ShopNest’s ProductListComponent binds *ngFor to products and uses (click) to add to cart.
Angular Angular Tutorial · Angular
Short answer: pplies CSS class when link's route is ctive ✅ Example: <a routerLink="/home" routerLinkActive="active-link">Home</a> ctive-link is applied when the current route is /home.
ngular? You define route parameters using : in the route path and extract them using ctivatedRoute. ✅ Defining Route: { path: 'product/:id', component: ProductDetailComponent } ✅ Navigating with params: <a [routerLink]="['/product', product.id]">View Details</a> ngular routing? Query params are passed using the URL (e.g., ?sort=price), and managed via the ctivatedRoute service. ✅ Add query params: this.router.navigate(['/products'], { queryParams: { sort: 'price' } }); ✅ Read query params: this.route.queryParams.subscribe(params => { console.log(params['sort']); }); in Angular? ctivatedRoute is a service that gives access to route-related data including: Route parameters… pplies CSS class…… }
return true;
}
} { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] } ✅ Summary Table: Feature Purpose RouterModule Enables routing in Angular routerLink Binds HTML element to a route routerLinkAct ive pplies class when route is active ctivatedRout Provides access to route params/query params Lazy Loading Loads feature modules only when needed canActivate Route guard to block unauthorized access Query Params Used for filters, search, sort (/products?sort=price) Nested Routes Embeds child routes within parent route Forms in Angular
Angular Angular Tutorial · Angular
Short answer: @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } }
@Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow';
}
}
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Angular Angular Tutorial · Angular
Short answer: An Angular application mainly consists of: Modules (NgModules) – containers for a cohesive block of code Components – control views (HTML + logic) Templates – HTML with Angular syntax Services – for business logic and reusable code Directives – modify the DOM Routing – navigation between views Real-Time Example: In a banking app: A LoginComponent A DashboardComponent A UserService to manage user data…
AppRoutingModule for navigation between login and dashboard
ShopNest’s ProductListComponent binds *ngFor to products and uses (click) to add to cart.
Angular Angular Tutorial · Angular
Short answer: Commonly done using: Login forms that send credentials to backend. Receive a token (usually JWT) to identify the user. Use Angular guards (like canActivate) to protect routes based on user roles. Store tokens securely (e.g., localStorage, sessionStorage, or cookies). Attach tokens to HTTP requests via HTTP Interceptors.
Angular Angular Tutorial · Angular
Short answer: Common techniques: Use OnPush change detection. Implement trackBy in *ngFor. Use lazy loading for modules. Avoid heavy computations in templates. Use pure pipes for filtering/formatting. Use memoization to cache expensive function results. Detach change detector manually for rarely updated components. Use ngZone.runOutsideAngular() for non-Angular async operations.
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Angular Angular Tutorial · Angular
Short answer: ✅
// app-routing.module.ts const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'about', component: AboutComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} The RouterModule is a built-in Angular module that provides routing directives, services, and configuration to manage navigation between views. ✅ Imports in App: import { RouterModule } from '@angular/router'; You use it with RouterModule.forRoot() (for root module) or RouterModule.forChild() (for feature modules with lazy loading). Angular? Routes are defined as an array of objects using the Routes type, and each route object maps a path to a component. ✅ Example: const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'products', component: ProductListComponent }, { path: 'products/:id', component: ProductDetailComponent }, { path: '**', component: NotFoundComponent } // wildcard route ]; Tools for Managing Routes: Route Guards Route Parameters Lazy Loading Query Params Nested Routes implemented? 🔸 Lazy Loading: Lazy loading is a technique to load feature modules only when needed, improving initial load performance. ✅ Implementation:
ShopNest’s ProductListComponent binds *ngFor to products and uses (click) to add to cart.
Angular Angular Tutorial · Angular
Short answer: These are attribute directives used to dynamically set styles or CSS classes.
➤ ngClass: Apply CSS classes <div [ngClass]="{'active': isActive, 'disabled': !isActive}"></div> ➤ ngStyle: Apply inline styles <div [ngStyle]="{'color': isError ?
user$ = this._user.asObservable(); setUser(user: User) { this._user.next(user); }
} ✅ 2. Using State Libraries NgRx (Redux pattern) Akita NGXS 📌 Real-Time Example: Store user data or app settings in a global AppStateService. Use the built-in HttpClient module for HTTP operations like GET, POST, PUT, DELETE. ✅ Example (GET request): constructor(private http: HttpClient) {} getUsers() { return this.http.get<User[]>('
} Ensure HttpClientModule is imported in AppModule. HttpClient is Angular’s built-in service for: Making HTTP requests (GET, POST, etc.) Automatically parsing JSON Supporting RxJS Observable streams Simplifying headers, error handling, etc. 📌 Real-Time Use: Fetching data from REST APIs Sending form data to the server Authentication and token handling HTTP requests? Use the catchError operator from RxJS to handle errors gracefully. ✅ Example: getUser() { return this.http.get('api/user').pipe( catchError(this.handleError) ); } handleError(error: HttpErrorResponse) { // Handle different error types return throwError(() => new Error('Something went wrong'));
} 📌 Real-Time Use Case: Show error toast if login fails Retry failed requests Navigate to error page (e.g., 404) work with HTTP requests? An Observable is a stream of asynchronous data. Angular HTTP methods return Observables using RxJS, allowing: Async operations (like API calls) Operators (map, filter, catchError) Subscription and cancellation ✅ Example: this.userService.getUsers().subscribe( users => this.users = users, error => console.error(error) ); 📌 Real-Time Use Case: Real-time data updates (e.g., chat, live stock prices) Async form submissions Progress indicators while loading data ✅ Summary Table: Concept Purpose Service Business logic & reusable functionality providedIn: 'root' Singleton service across app HttpClient Makes API calls, returns observables Observable Handles async data streams (e.g., HTTP) catchError Handles errors in HTTP requests AppStateServic Global state storage using RxJS (BehaviorSubject, etc.) RxJS (Reactive Programming) RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables to handle asynchronous data streams. To manage async operations (e.g., HTTP calls) For real-time event streams (like user input, socket, etc.) For composition and transformation of data streams It's the foundation of Angular’s reactive programming model, especially HttpClient, Forms, and Router. An Observable is a stream of data that can be observed over time. Observables emit values (0, 1, or many), errors, or a completion signal. ✅ Example: const observable = new Observable(observer => { observer.next('Data 1'); observer.next('Data 2'); observer.complete(); }); In Angular: this.http.get('api/data') // returns an Observable Promise? Feature Observable Promise Multiple Values ✅ Emits multiple values ❌ Resolves once Lazy Execution ✅ Executes only when subscribed ✅ Executes immediately Cancelable ✅ Can be cancelled via unsubscribe() ❌ Not cancelable Operators ✅ Chainable with RxJS operators ❌ Limited transformation Built-in in Angular ✅ Used by Angular APIs ✅ Supported for some features ✅ Use-case: Use Observable when dealing with: HTTP streams WebSocket streams User input streams Real-time data An Observer is an object with next(), error(), and complete() methods that receives notifications from an Observable. ✅ Example: const observer = { next: value => console.log('Received:', value), error: err => console.error('Error:', err), complete: () => console.log('Completed') }; observable.subscribe(observer); RxJS? The subscribe() method connects an Observer to an Observable. Once subscribed, the observer starts receiving emitted values. ✅ Example: myObservable.subscribe( value => console.log(value), // next error => console.error(error), // error () => console.log('Done') // complete ); examples of commonly used operators? Operators are functions used to transform, filter, combine, or control Observable streams. Operator Purpose map Transform emitted values filter Filter values based on condition mergeMap Flatten inner Observables concurrently switchMap Cancel previous Observable and switch concatMap Queue Observables, run one after another take Take first N values debounceT ime Delay emissions for a time catchErro Handle errors in stream and concatMap operators used for? ✅ map: Transform value source$.pipe(map(x => x * 2)) ✅ filter: Emit only values that meet condition source$.pipe(filter(x => x > 10)) ✅ mergeMap: Flatten Observables in parallel click$.pipe(mergeMap(() => http.get('/api'))) ✅ switchMap: Cancel previous Observable and switch to new one search$.pipe( debounceTime(300), switchMap(query => http.get(`/search?q=${query}`)) ✅ concatMap: Queue Observables sequentially tasks$.pipe(concatMap(task => http.post('/do', task))) using RxJS? ✅ Use forkJoin (all in parallel, wait until all complete): forkJoin({ user: this.http.get('/user'), orders: this.http.get('/orders') }).subscribe(data => { console.log(data.user, data.orders); }); ✅ Use mergeMap for dependent requests: this.http.get('/user').pipe( mergeMap(user => this.http.get(`/orders?userId=${user.id}`)) ).subscribe(...) different from an Observable? Feature Observable Subject Emits values Producer only Both producer and consumer Multicast ❌ No – one subscriber per emission ✅ Yes – shares data to many Use-case External data sources Manual or user-driven events ✅ Example: const subject = new Subject<number>();
subject.subscribe(val => console.log('A:', val));
Angular Angular Tutorial · Angular
Short answer: Can you give examples? Directives are instructions in the DOM. They help Angular extend HTML's capabilities. Types of Directives:
A shared CartService is injected into header and product pages so both see the same cart count.
Angular Angular Tutorial · Angular
Short answer: Break down large components: Divide UI into smaller, reusable child components.
Use container/presentation pattern: Container components handle logic and data fetching. Presentation components are dumb, focus on UI. Move logic to services or state management. Avoid large inline templates and styles; use separate files. Use OnPush change detection strategy to optimize performance. Use reactive forms or observables to keep code clean.
ShopNest’s ProductListComponent binds *ngFor to products and uses (click) to add to cart.
Angular Angular Tutorial · Angular
Short answer: The Angular compiler converts Angular templates and TypeScript code into efficient JavaScript code. There are two modes: JIT (Just-in-Time): Compilation happens in the browser at runtime. AOT (Ahead-of-Time): Compilation happens during the build phase, producing optimized JS files. It processes: Templates → render functions Metadata → static code to improve runtime Ivy compiler is the latest Angular compiler.
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Angular Angular Tutorial · Angular
Short answer: uthorization in Angular? Commonly done using: Login forms that send credentials to backend. Receive a token (usually JWT) to identify the user. Use Angular guards (like canActivate) to protect routes based on user roles. Store tokens securely (e.g., localStorage, sessionStorage, or cookies). Attach tokens to HTTP requests via HTTP… Interceptors.
Angular Angular Tutorial · Angular
Short answer: TestBed is the primary API to configure and initialize the environment for unit testing Angular components and services. It allows you to declare components, provide services, import modules, and compile templates.
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Angular Angular Tutorial · Angular
Short answer: Use npm or yarn to install the package: npm install lodash If the library requires it, add typings: npm install --save-dev @types/lodash Some libraries have Angular-specific schematics that you can add via: ng add @angular/material This command installs and configures Angular Material automatically.
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Angular Angular Tutorial · Angular
Short answer: To use a module’s components/directives/pipes, import it in your module’s imports array. To make components/directives/pipes available to other modules, export them in your module’s exports array.
@NgModule({ imports: [CommonModule], exports: [MyComponent, MyDirective] }) export class SharedModule {} Then import SharedModule in any module where you want to use those components.
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Angular Angular Tutorial · Angular
Short answer: Applications? Common techniques: Use OnPush change detection. Implement trackBy in *ngFor. Use lazy loading for modules. Avoid heavy computations in templates. Use pure pipes for filtering/formatting. Use memoization to cache expensive function results. Detach change detector manually for rarely updated components. Use… ngZone.runOutsideAngular() for…
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Angular Angular Tutorial · Angular
Short answer: ✅
this.profileForm = new FormGroup({ firstName: new FormControl('', Validators.required), lastName: new FormControl(''), email: new FormControl('', [Validators.required, Validators.email]) }); <form [formGroup]="profileForm" (ngSubmit)="onSubmit()"> <input formControlName="firstName" /> <input formControlName="lastName" /> <input formControlName="email" /> <button type="submit">Submit</button> </form>
ShopNest’s ProductListComponent binds *ngFor to products and uses (click) to add to cart.
Angular Angular Tutorial · Angular
Short answer: Use built-in validators via HTML attributes like required, minlength. Use Angular directives like #username="ngModel" to check validity. ✅
<input name="email" ngModel required email #email="ngModel" /> <div *ngIf="email.invalid && email.touched"> <small *ngIf="email.errors?.required">Email is required</small> <small *ngIf="email.errors?.email">Invalid email format</small> </div>
ShopNest’s ProductListComponent binds *ngFor to products and uses (click) to add to cart.
Angular Angular Tutorial · Angular
Short answer: And configuration to manage navigation between views.
✅ Imports in App: import { RouterModule } from '@angular/router'; You use it with RouterModule.forRoot() (for root module) or RouterModule.forChild() (for feature modules with lazy loading). const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'products', component: ProductListComponent }, { path: 'products/:id', component: ProductDetailComponent }, { path: '**', component: NotFoundComponent } // wildcard route ]; Tools for Managing Routes: Route Guards Route Parameters Lazy Loading Query Params Nested Routes implemented? 🔸 Lazy Loading: Lazy loading is a technique to load feature modules only when needed, improving initial load performance. ✅ Implementation:
ShopNest’s ProductListComponent binds *ngFor to products and uses (click) to add to cart.
Angular Angular Tutorial · Angular
Short answer: Examples: <!-- *ngIf --> <div *ngIf="user.isLoggedIn">Welcome, {{ user.name }}</div> <!-- *ngFor --> <li *ngFor="let item of items">{{ item }}</li> Real-Time Example: In a to-do app, *ngFor is used to loop through tasks and display them.
A shared CartService is injected into header and product pages so both see the same cart count.
Angular Angular Tutorial · Angular
Short answer: Directives are instructions in the DOM. They help Angular extend HTML's capabilities. Types of Directives:
A shared CartService is injected into header and product pages so both see the same cart count.
Angular Angular Tutorial · Angular
Short answer: XSS (Cross-Site Scripting) Protection: Angular automatically sanitizes dangerous content in templates (e.g., {{ userInput }}).
Use DomSanitizer for trusted content. Binding syntax prevents direct HTML injection. CSRF (Cross-Site Request Forgery) Protection: Angular’s HttpClient works with backend CSRF tokens. Common approach: Backend sends CSRF token, Angular sends it back via headers or cookies. Developers must implement token handling in interceptors.
Angular Angular Tutorial · Angular
Short answer: Provide a mock implementation of the service in TestBed using the providers array. Use useClass, useValue, or useFactory to inject mocks.
class MockDataService { getData() { return of(['mock data']); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: DataService, useClass: MockDataService }] }); });
A shared CartService is injected into header and product pages so both see the same cart count.
Angular Angular Tutorial · Angular
Short answer: trackBy is a function used with *ngFor to tell Angular how to track list items uniquely. Why it matters: Without trackBy, Angular recreates DOM elements on each update, causing performance overhead. ✅
<div *ngFor="let item of items; trackBy: trackById"> {{ item.name }} </div> trackById(index: number, item: any) { return item.id; // unique id per item } Angular reuses existing DOM elements instead of recreating them.
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.
Install Toolliyo like an app Free
Home-screen access to tutorials, coding practice & career tools — no app store needed.
On iPhone/iPad: tap Share then Add to Home Screen.