β 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
<mat-toolbar color="primary">My App</mat-toolbar>
<mat-card>
<mat-card-title>Welcome</mat-card-title>
</mat-card>
β 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';
}
}
<p appHighlight>This text is highlighted.</p>
β 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.
<p>Hello, {{ name }}</p>
πΉ 2. Property Binding ([property]
)
Binds component data to HTML property.
<img [src]="imgUrl">
πΉ 3. Event Binding ((event)
)
Handles user events like clicks.
<button (click)="onClick()">Click Me</button>
πΉ 4. Two-way Binding ([(ngModel)]
)
Syncs data both ways.
<input [(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 }} <!-- Output: olleh -->
β 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.
<router-outlet></router-outlet>
πΈ RouterLink
Binds to route paths in your templates.
<a routerLink="/home">Go to Home</a>
β
11. What happens when you use the <script>
tag within a template?
Using <script>
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
<script>
tags in the DOM. -
Best Practice Violation: Script logic should go in the component
.ts
file, not in the template.
π§ Instead of this:
<!-- β Not recommended -->
<script>alert('Hi')</script>
β 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:
<div *ngIf="show" #myDiv>Hello</div>
@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 <ng-content> 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
<router-outlet>
acts as a placeholder where routed components are rendered.
β Example:
<nav>
<a routerLink="/home">Home</a>
</nav>
<router-outlet></router-outlet>
Defined in app-routing.module.ts
:
const routes: Routes = [
{ path: 'home', component: HomeComponent }
];
β
37. Can We Use Multiple <router-outlet>
?
Yes β useful for layouts with named outlets.
β Example:
<router-outlet></router-outlet> <!-- Primary -->
<router-outlet name="popup"></router-outlet> <!-- Secondary -->
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: `<p>Hello!</p>`
})
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: `<p>User Component</p>`
})
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:
<ng-template #container></ng-template>
β 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: `<h1>Hello!</h1>`,
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) {
<expensive-component></expensive-component>
}
β 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+.
Top comments (0)