Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
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: 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: 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: gainst XSS and CSRF? XSS (Cross-Site Scripting) Protection: Angular automatically sanitizes dangerous content in templates (e.g., {{ userInput }}). Use DomSanitizer for trusted content. Binding syntax preve…
Short answer: rray. Use useClass, useValue, or useFactory to inject mocks. class MockDataService { getData() { return of(['mock data']); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: D…
Short answer: Use Ahead-of-Time (AOT) compilation for faster rendering. Explain a bit more Enable production builds (ng build --prod) with optimizations: Minification Tree shaking Dead code elimination Use lazy loading f…
Short answer: And faster repeat loads. Optimize images and assets (compress, lazy load). Use OnPush change detection for components to reduce unnecessary UI updates. Avoid memory leaks by unsubscribing from observables.…
Short answer: NgRx is a Redux-inspired state management library for Angular. Uses Actions, Reducers, Store, and Effects to handle application state predictably. Centralizes state for easy debugging, time-travel, and immu…
Short answer: Use the production flag with ng build: ng build --prod This enables: AOT compilation (Ahead-of-Time) Minification and Uglification of code Tree shaking to remove unused code Bundling for fewer HTTP requests…
Short answer: ChangeDetectorRef allows you to manually control change detection: detectChanges(): Run change detection immediately. markForCheck(): Mark component to check in next cycle. detach(): Stop change detection f…
Short answer: Unsubscribe from Observables using: takeUntil with a destroy notifier. async pipe which auto-unsubscribes. Remove event listeners added manually. Avoid retaining references to DOM or large objects. Use tool…
Short answer: Create a validator function returning an error object or null. Explain a bit more ✅ Example (Custom validator checking forbidden name): function forbiddenNameValidator(nameRe: RegExp): ValidatorFn { return…
Short answer: Name some commonly used decorators. Decorators are functions that add metadata to classes, methods, or properties. Common Angular Decorators: Decorator Description @Componen Declares a component @NgModule D…
Short answer: Applications? Unsubscribe from Observables using: takeUntil with a destroy notifier. async pipe which auto-unsubscribes. Remove event listeners added manually. Avoid retaining references to DOM or large obj…
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: 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: 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: gainst XSS and CSRF? 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: rray. Use useClass, useValue, or useFactory to inject mocks. class MockDataService { getData() { return of(['mock data']); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: DataService, useClass: MockDataService }] }); }); rray. Use useClass, useValue, or useFactory to inject mocks.
… class MockDataService {… getData() { return of(['mock data']); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: DataService, useClass: MockDataService }] }); }); rray. Use useClass, useValue, or useFactory to inject mocks. Example: class MockDataService { getData() { return of(['mock data']); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: DataService, useClass: MockDataService }] }); }); rray. Use useClass, useValue, or useFactory to inject mocks. Example:… 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: Use Ahead-of-Time (AOT) compilation for faster rendering.
Enable production builds (ng build --prod) with optimizations: Minification Tree shaking Dead code elimination Use lazy loading for feature modules. Bundle analysis: Use tools like source-map-explorer to find large bundles. Use Angular’s built-in caching and service workers (via Angular PWA) for offline and faster repeat loads. Optimize images and assets (compress, lazy load). Use OnPush change detection for components to reduce unnecessary UI updates. Avoid memory leaks by unsubscribing from observables. Use trackBy function with *ngFor to optimize DOM updates.
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: And faster repeat loads. Optimize images and assets (compress, lazy load). Use OnPush change detection for components to reduce unnecessary UI updates. Avoid memory leaks by unsubscribing from observables. Use trackBy function with *ngFor to optimize DOM updates.
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: NgRx is a Redux-inspired state management library for Angular. Uses Actions, Reducers, Store, and Effects to handle application state predictably. Centralizes state for easy debugging, time-travel, and immutability. Ideal for complex apps requiring consistent global state management.
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 the production flag with ng build: ng build --prod This enables: AOT compilation (Ahead-of-Time) Minification and Uglification of code Tree shaking to remove unused code Bundling for fewer HTTP requests Enables optimizations in angular.json
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: ChangeDetectorRef allows you to manually control change detection: detectChanges(): Run change detection immediately. markForCheck(): Mark component to check in next cycle. detach(): Stop change detection for component. reattach(): Resume change detection. ✅
constructor(private cd: ChangeDetectorRef) {} updateData() { this.data = fetchNewData(); this.cd.detectChanges(); // manually trigger update }
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: Unsubscribe from Observables using: takeUntil with a destroy notifier. async pipe which auto-unsubscribes. Remove event listeners added manually. Avoid retaining references to DOM or large objects. Use tools like Chrome DevTools and Angular Profiler.
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: Create a validator function returning an error object or null.
✅ Example (Custom validator checking forbidden name): function forbiddenNameValidator(nameRe: RegExp): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { const forbidden = nameRe.test(control.value); return forbidden ? { forbiddenName: { value: control.value } } : null; }; } // Usage: new FormControl('', [forbiddenNameValidator(/admin/i)])
Create a validator function returning an error object or null. ✅ Example (Custom validator checking forbidden name): function forbiddenNameValidator(nameRe: RegExp): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => {
const forbidden = nameRe.test(control.value);
return forbidden ? { forbiddenName: { value: control.value } } : null; }; } // Usage: new FormControl('', [forbiddenNameValidator(/admin/i)])
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: Name some commonly used decorators. Decorators are functions that add metadata to classes, methods, or properties. Common Angular Decorators: Decorator Description @Componen Declares a component @NgModule Declares a module @Injectab le Declares a service for DI @Input() Pass data from parent to child @Output() Emit events from child to parent @Directiv Create custom directives
@Component({ selector: 'app-header', templateUrl: './header.component.html' }) Real-Time Example: Use @Input() in a product card to pass product details from a parent ProductListComponent.
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? Unsubscribe from Observables using: takeUntil with a destroy notifier. async pipe which auto-unsubscribes. Remove event listeners added manually. Avoid retaining references to DOM or large objects. Use tools like Chrome DevTools and Angular Profiler.
ShopNest admin can be built in Angular with modules/components, services for API calls, and reactive forms for product edit.