✅ 1. What is Angular, and why does Angular use TypeScript?
🔹 Angular:
Angular is a TypeScript-based open-source front-end framework developed by Google for building dynamic web applications. It follows component-based architecture and comes with a powerful set of features like:
- Two-way data binding
- Dependency Injection
- RxJS support
- Routing
- Form validation
- Modular development
🔹 Why TypeScript?
TypeScript is a superset of JavaScript that adds static typing and OOP features like classes, interfaces, and access modifiers.
🧠 Key Reasons Angular uses TypeScript:
- Type Safety: Helps catch errors during development.
- Tooling Support: Better autocompletion and refactoring with IDEs.
- OOP Support: Facilitates modular architecture with interfaces and decorators.
-
Advanced Features: Decorators (
@Component
,@Injectable
) are native to TypeScript.
✅ Real-world analogy:
Using TypeScript in Angular is like driving a car with ABS and sensors — it keeps you safe by warning about issues before they become real problems in production.
✅ 2. What is Angular Material?
Angular Material is a UI component library developed by Angular team following the Material Design principles by Google.
🔹 Features:
- Pre-built UI components (buttons, dialogs, date pickers, tabs)
- Responsive layout using
Flex Layout
- Accessible and mobile-friendly
- Customizable themes
🔹 Example:
ng add @angular/material
color="primary">My App
Welcome
✅ Scenario:
Use Angular Material when you want to build a consistent UI quickly without reinventing the wheel. Ideal for dashboards, admin panels, or enterprise apps.
✅ 3. What is a directive, and what are the types of directives?
🔹 A directive in Angular is a class with a @Directive
decorator that lets you manipulate the DOM or component behavior.
🔸 Types of Directives:
-
Component Directive – Technically a directive with a template.
- e.g.,
@Component
- e.g.,
-
Structural Directive – Changes the DOM structure
- e.g.,
*ngIf
,*ngFor
,*ngSwitch
- e.g.,
-
Attribute Directive – Alters the appearance or behavior of an element.
- e.g.,
ngClass
,ngStyle
, or custom ones
- e.g.,
🔹 Example: Custom Attribute Directive
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
appHighlight>This text is highlighted.
✅ 4. What are the building blocks of Angular?
-
Modules (
NgModules
) – Group related features - Components – UI + logic (template + TS class)
- Templates – HTML with Angular syntax
- Directives – Modify DOM or behavior
- Services – Business logic, data access, reusable code
- Routing – Navigation and views
- Pipes – Transform data in templates
- Dependency Injection (DI) – Service injection
✅ 5. What is Dependency Injection (DI)?
DI is a design pattern where dependencies (services, config, etc.) are injected into components instead of hard-coding them.
🔹 Benefits:
- Loose coupling
- Easier testing
- Better reusability
🔹 Example:
@Injectable({ providedIn: 'root' })
export class LoggerService {
log(msg: string) {
console.log(msg);
}
}
@Component({ ... })
export class HomeComponent {
constructor(private logger: LoggerService) {
this.logger.log('Home loaded');
}
}
✅ Real-world analogy:
It’s like ordering a pizza instead of baking one yourself — let someone else handle it and just enjoy the result.
✅ 6. What is Data Binding, and how many ways can it be implemented?
Data binding connects component logic with the UI.
🔹 1. Interpolation ({{ }}
)
Displays dynamic data.
Hello, {{ name }}
🔹 2. Property Binding ([property]
)
Binds component data to HTML property.
[src]="imgUrl">
🔹 3. Event Binding ((event)
)
Handles user events like clicks.
(click)="onClick()">Click Me
🔹 4. Two-way Binding ([(ngModel)]
)
Syncs data both ways.
[(ngModel)]="username">
✅ 7. What are filters in Angular?
In Angular, Pipes are the equivalent of filters (from AngularJS).
🔹 Built-in Pipes:
-
date
,uppercase
,lowercase
,currency
,percent
, etc.
🔹 Custom Pipe Example:
@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
Usage:
{{ 'hello' | reverse }}
✅ 8. What is ViewEncapsulation?
Controls how CSS styles are scoped to a component.
🔸 Types:
- Emulated (default): Styles scoped via unique attributes
- None: Styles are global
- ShadowDom: Uses native Shadow DOM
✅ Example:
@Component({
...
encapsulation: ViewEncapsulation.Emulated // or None / ShadowDom
})
✅ 9. Why prioritize TypeScript over JavaScript in Angular?
🔹 Reasons:
- Static typing → Fewer runtime errors
- Decorators → Metadata and Dependency Injection
- Better tooling → IntelliSense, refactoring
- Interfaces, enums, access modifiers
- Ahead-of-time (AOT) compatibility
Angular is written in TypeScript, making it a natural fit.
✅ 10. What do you understand by RouterOutlet and RouterLink?
🔸 RouterOutlet
A directive that marks where the routed component should be displayed.
🔸 RouterLink
Binds to route paths in your templates.
routerLink="/home">Go to Home
✅ 11. What happens when you use the
tag within a template?
Using tags inside Angular templates is strongly discouraged and generally not supported.
🔥 Why it's a problem:
- Security Risk: Angular sanitizes templates to prevent XSS attacks.
-
Ignored Content: Angular will ignore or strip out
tags in the DOM.
-
Best Practice Violation: Script logic should go in the component
.ts
file, not in the template.
🧠 Instead of this:
alert('Hi')
✅ Do this:
ngOnInit() {
alert('Hi');
}
✅ 12. What is ViewChild
, and when would you use { static: false }
?
🔹 @ViewChild
It allows access to a DOM element, directive, or component inside your template from your component class.
Syntax:
@ViewChild('myElement', { static: false }) myEl: ElementRef;
🔹 static: false
Use when the element is inside an *ngIf
, *ngFor
, or any structural directive and you want to access it after the view initializes (ngAfterViewInit
).
🔹 static: true
Use when the element is always present and you want to access it in ngOnInit
.
✅ Example:
*ngIf="show" #myDiv>Hello
@ViewChild('myDiv', { static: false }) myDiv: ElementRef;
✅ 13. How many ways can we share data between components?
🔸 1. @Input() / @Output()
- Parent → Child:
@Input()
- Child → Parent:
@Output()
with EventEmitter
🔸 2. Shared Service with BehaviorSubject or Subject
Best for unrelated components (e.g., sibling to sibling).
🔸 3. Router State / Route Params
Pass data during routing.
🔸 4. ngRx / State Management
Advanced: used in large-scale apps.
✅ Example:
// service.ts
data$ = new BehaviorSubject<string>('initial');
// component A
this.service.data$.next('new value');
// component B
this.service.data$.subscribe(value => this.received = value);
✅ 14. Angular Lifecycle Hooks
These are methods that allow you to tap into different phases of a component's lifecycle.
Hook | When it’s called |
---|---|
ngOnChanges() |
When an input-bound property changes |
ngOnInit() |
After component initialization |
ngDoCheck() |
Custom change detection |
ngAfterContentInit() |
After is projected |
ngAfterContentChecked() |
After content is checked |
ngAfterViewInit() |
After component’s view is initialized |
ngAfterViewChecked() |
After the view and child views are checked |
ngOnDestroy() |
Just before component is destroyed |
✅ Example:
ngOnInit() {
console.log("Component initialized");
}
✅ 15. What is AOT compilation? What are the advantages of AOT?
🔹 AOT (Ahead-of-Time Compilation)
Angular compiles HTML and TypeScript into JavaScript at build time, rather than in the browser.
🔸 Advantages:
- Faster Rendering: Templates are pre-compiled.
- Smaller Bundle Size
- Early Error Detection
- Security: Template injection attacks are minimized.
✅ Usage:
AOT is enabled by default in production:
ng build --prod
✅ 16. What is "sourceMap": true
in Angular?
In angular.json
, this config generates source maps that map minified code back to the original TypeScript code.
✅ Why it’s useful:
- Enables debugging in the browser (e.g., Chrome DevTools)
- Maps back errors to actual
.ts
files instead of.js
✅ 17. What is RxJS?
RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables.
🔹 Core Concepts:
- Observable: Represents a stream of data.
- Observer: Consumes the data.
-
Operators: Transform data (e.g.,
map
,filter
,mergeMap
)
✅ Example:
interval(1000).pipe(
map(x => x * 2)
).subscribe(console.log);
✅ 18. Promise vs Observable
Feature | Promise | Observable |
---|---|---|
Eager vs Lazy | Eager | Lazy |
Values | One | Multiple |
Cancelable | ❌ | ✅ |
Operators | ❌ | ✅ |
Async Operations | ✅ | ✅ |
✅ Example:
// Promise
fetchData().then(res => ...);
// Observable
this.service.getData().subscribe(res => ...);
✅ 19. What are Template and Reactive Forms?
🔹 Template-driven Forms
- Use
ngModel
- Simpler, best for basic forms
- Defined in HTML
🔹 Reactive Forms
- Use
FormGroup
,FormControl
,FormBuilder
- More robust and testable
- Defined in TypeScript
✅ Example:
this.form = new FormGroup({
name: new FormControl('')
});
✅ 20. What are forRoot()
and forChild()
in Angular?
🔹 forRoot()
Used in root module to configure global providers or singletons.
🔹 forChild()
Used in feature modules to prevent re-instantiating services.
✅ Example:
RouterModule.forRoot(routes) // AppModule
RouterModule.forChild(childRoutes) // FeatureModule
✅ 21. How to handle multiple HTTP requests in Angular?
Use RxJS operators like forkJoin
, combineLatest
, zip
, or merge
.
✅ forkJoin
Example:
forkJoin([
this.service.getUser(),
this.service.getOrders()
]).subscribe(([user, orders]) => {
console.log(user, orders);
});
-
forkJoin
waits for all Observables to complete.
✅ 22. Map vs mergeMap vs switchMap vs concatMap
Operator | Behavior |
---|---|
map |
Transforms values |
mergeMap |
Flattens & merges inner Observables concurrently |
switchMap |
Cancels previous, switches to new Observable |
concatMap |
Runs requests sequentially |
✅ Example:
search$.pipe(
debounceTime(300),
switchMap(term => this.api.search(term))
)
switchMap
is great for search/autocomplete where you want the latest request only.
✅ 23. What are class decorators?
Class decorators add metadata or modify behavior of classes.
✅ Common Angular Class Decorators:
@Component
@Injectable
@Directive
@NgModule
Example:
@Injectable({ providedIn: 'root' })
export class MyService {}
✅ 24. What is the @Component
Decorator in Angular?
Used to define a component and its metadata.
✅ Example:
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent {}
✅ 25. What is Bundle Analysis in Angular?
Used to inspect and reduce the size of the production bundle.
✅ Tools:
- Angular CLI:
ng build --stats-json
ng build --configuration production --stats-json
Helps:
- Find large packages
- Remove unused code
- Improve load time
✅ 26. When to Use PUT and PATCH?
Method | Use Case |
---|---|
PUT |
Replace the entire resource |
PATCH |
Update part of the resource |
Example:
// PUT - Replace
this.http.put('/api/user/1', userData);
// PATCH - Update only part
this.http.patch('/api/user/1', { name: 'New Name' });
✅ 27. What is the purpose of angular.json
?
This is the Angular workspace configuration file.
It configures:
- Build and serve targets
- Assets, styles, scripts
- File replacements (e.g., environments)
- Linting and testing
✅ 28. Angular 17 New Features (Highlights)
-
Deferrable Views: Lazy load components at a finer granularity using
@defer
-
Control Flow Syntax: Built-in
@if
,@for
,@switch
(no more*ngIf
,*ngFor
) - Standalone Project Structure by Default
- Signal-based reactivity (experimental)
- Zone-less by default for faster change detection
✅ 29. Difference: Standard Component vs Standalone Component
Feature | Standard Component | Standalone Component |
---|---|---|
Module required? | Yes | No |
Declaration | In @NgModule
|
standalone: true |
Angular 14+ | ❌ | ✅ |
✅ Example:
@Component({
standalone: true,
imports: [CommonModule],
template: `...`
})
export class MyStandaloneComponent {}
✅ 30. What is bootstrapModule
in Angular?
It's the method Angular uses to launch the root module.
✅ Example:
platformBrowserDynamic().bootstrapModule(AppModule);
In standalone component apps (Angular 17+), it can also bootstrap a component:
bootstrapApplication(AppComponent);
✅ 31. Angular Testing Framework
Angular uses Jasmine for writing tests and Karma for running them.
🔹 Key Concepts:
- TestBed: Angular testing environment setup
- Fixtures: Handle component instances
- Spies: Mock services/functions
✅ Example (Component Test):
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});
it('should create the component', () => {
expect(component).toBeTruthy();
});
it('should have title "MyApp"', () => {
component.title = 'MyApp';
fixture.detectChanges();
expect(component.title).toBe('MyApp');
});
});
✅ 32. Pre-fetch Your Data Using Resolvers
Resolvers fetch data before navigating to a route.
✅ Use case: Prevents component from loading with incomplete data.
✅ Steps:
- Create a Resolver:
@Injectable({ providedIn: 'root' })
export class UserResolver implements Resolve<User> {
constructor(private service: UserService) {}
resolve(route: ActivatedRouteSnapshot): Observable<User> {
return this.service.getUserById(route.paramMap.get('id'));
}
}
- Add it to route:
{
path: 'user/:id',
component: UserComponent,
resolve: { user: UserResolver }
}
- In component:
this.route.data.subscribe(data => {
this.user = data.user;
});
✅ 33. Guard in Angular
Guards control access to routes.
🔸 Types:
CanActivate
CanDeactivate
CanLoad
Resolve
CanActivateChild
✅ Example (CanActivate
):
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
Apply it to route:
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
✅ 34. HostBinding and HostListener
These allow interaction with the host element of the component or directive.
✅ @HostBinding
Example:
@HostBinding('class.active') isActive = true;
✅ @HostListener
Example:
@HostListener('click', ['$event'])
onClick(event: Event) {
console.log('Element clicked!', event);
}
Used frequently in custom directives.
✅ 35. Polyfill in Angular
Polyfills provide browser compatibility for features not supported in older browsers.
✅ Config:
Check polyfills.ts
file in Angular project.
// Example polyfill for ES6 features
import 'core-js/es6';
Most modern Angular apps only need a few because of evergreen browser support.
✅ 36. RouterOutlet in Angular
acts as a placeholder where routed components are rendered.
✅ Example:
routerLink="/home">Home
Defined in app-routing.module.ts
:
const routes: Routes = [
{ path: 'home', component: HomeComponent }
];
✅ 37. Can We Use Multiple
?
Yes — useful for layouts with named outlets.
✅ Example:
name="popup">
Routes:
{
path: 'help',
component: HelpComponent,
outlet: 'popup'
}
Activate via:
this.router.navigate([{ outlets: { popup: ['help'] } }]);
✅ 38. Can I Write a Component Without a Constructor?
Yes — but only if the component does not need any DI services.
✅ Minimal Example:
@Component({
selector: 'app-hello',
template: `Hello!`
})
export class HelloComponent {}
If you need services like HttpClient
, you’ll need a constructor.
✅ 39. Pure Pipe vs Impure Pipe
Pipe Type | Trigger |
---|---|
Pure (default) | Called only when input changes |
Impure | Called on every change detection cycle |
✅ Pure Pipe Example:
@Pipe({ name: 'purePipe' })
export class PurePipe implements PipeTransform {
transform(value: number): number {
return value * 2;
}
}
✅ Impure Pipe:
@Pipe({ name: 'impurePipe', pure: false })
Use impure pipes carefully — they affect performance!
✅ 40. FormBuilder vs FormGroup in Angular
Both are part of Reactive Forms.
Concept | Use Case |
---|---|
FormGroup |
Manually create controls |
FormBuilder |
Shorthand, more concise |
✅ FormGroup Example:
this.form = new FormGroup({
name: new FormControl(''),
age: new FormControl('')
});
✅ FormBuilder Example:
constructor(private fb: FormBuilder) {}
this.form = this.fb.group({
name: [''],
age: ['']
});
✅ 41. View Encapsulation in Angular (Recap)
Angular uses View Encapsulation to control style scoping.
🔸 Modes:
Mode | Description |
---|---|
Emulated (default) |
Emulates Shadow DOM by adding unique attributes |
None |
No encapsulation; styles are global |
ShadowDom |
Uses browser-native Shadow DOM (real encapsulation) |
✅ Example:
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css'],
encapsulation: ViewEncapsulation.Emulated
})
✅ Use Case:
- Use
None
for global themes (e.g., Angular Material theming). - Use
ShadowDom
for strict style isolation.
✅ 42. Difference Between Modules and Components
Feature | Module | Component |
---|---|---|
Purpose | Group related components/services | Represent UI elements/pages |
Decorator | @NgModule |
@Component |
Structure | Logical grouping | Visual/UI rendering |
✅ Example:
@NgModule({
declarations: [UserComponent],
imports: [CommonModule],
})
export class UserModule {}
@Component({
selector: 'app-user',
template: `User Component`
})
export class UserComponent {}
✅ 43. Lazy Loading in Angular
Lazy loading loads modules on demand, improving initial load time.
✅ Setup:
- Create a feature module (e.g.,
admin.module.ts
) - Use
loadChildren
in the route:
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
Ensure AdminModule
has its own routing (AdminRoutingModule
) with its components.
✅ 44. Dynamic Component Loading
Use ViewContainerRef
and ComponentFactoryResolver
to load components dynamically.
✅ Example:
@ViewChild('container', { read: ViewContainerRef }) container!: ViewContainerRef;
constructor(private cfr: ComponentFactoryResolver) {}
loadComponent() {
import('./dynamic/dynamic.component').then(({ DynamicComponent }) => {
this.container.clear();
this.container.createComponent(DynamicComponent);
});
}
Template:
#container>
✅ 45. Change Detection in Angular
Angular uses zone.js to trigger change detection automatically on async events.
🔸 Strategies:
- Default: Detects all changes (slower)
- OnPush: Detects changes only for input-bound values
✅ Example:
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
✅ Improve Performance:
- Use
OnPush
when using immutables and@Input
- Detach CD manually in performance-heavy components
✅ 46. Zone.js in Angular
zone.js
patches async APIs (e.g., setTimeout, Promise) to notify Angular of state changes.
🔹 Without zone.js, Angular wouldn't know when to run change detection.
With Angular 17, zone-less change detection using Signals
is becoming the default.
✅ 47. Signals in Angular 17
Signals
offer a reactivity model without needing zone.js or manual subscription management.
✅ Setup:
import { signal, computed, effect } from '@angular/core';
count = signal(0);
double = computed(() => this.count() * 2);
effect(() => console.log(this.double()));
✅ Benefit:
- Fine-grained reactivity
- Works without zones
- Declarative like React’s useState/useEffect
✅ 48. Standalone Components
No need for NgModules
. Useful for reducing boilerplate.
✅ Example:
@Component({
selector: 'app-home',
standalone: true,
template: `Hello!`,
imports: [CommonModule]
})
export class HomeComponent {}
✅ Bootstrap App with Standalone:
bootstrapApplication(HomeComponent);
✅ 49. Defer Blocks in Angular 17
@defer
is used to lazy load parts of templates (not just routes!).
✅ Example:
@defer (when visible) {
}
✅ Use Cases:
- Load chart, table, or modal only when visible
- Improve First Contentful Paint (FCP)
✅ 50. @Input, @Output vs Signals
Feature | @Input/@Output | Signals |
---|---|---|
Data Flow | Parent → Child / Child → Parent | Bi-directional and reactive |
Reactive? | No | Yes |
Boilerplate | More | Less |
Angular Version | Stable since v2 | Angular 16+ |
✅ Signal Example:
count = signal(0);
increment() {
this.count.set(this.count() + 1);
}
✅ When to Use:
- Use
@Input/@Output
for compatibility. - Use Signals for state management and zone-less CD in Angular 17+.