1.Angular Basics
Angular is built on top of TypeScript and is known for its modularity, reactivity, and maintainability.
- Angular Versions: Angular is frequently updated. By Angular 19, notable updates include standalone components, typed forms, and Signal API for state management.
- Monorepo: Angular CLI supports monorepo architecture using tools like Nx for managing multiple projects.
2. Components
- Purpose: Components define the user interface logic and the visual structure of the app.
- Components are the building blocks of an Angular app, defining the structure and logic for UI elements.
- Selector: Used to embed the component.
- Template: Defines the HTML.
- Styles: Apply CSS scoped to the component.
Example:
@Component({
selector: 'app-hello',
template: '<h1>Hello {{name}}</h1>',
styleUrls: ['./hello.component.css'],
})
export class HelloComponent {
name = 'Angular';
}
*Templates *
-
Templates are HTML-like syntax, enriched with Angular directives for dynamic rendering.
- Interpolation:
{{ username }}
- Property Binding:
<input [value]="username" />
- Event Binding:
<button (click)="greet()">Click Me</button>
Component Communication:
1.Parent to Child: Using @Input properties.
@Input() data: string;
2.Child to Parent: Using @Output with EventEmitter.
@Output() notify = new EventEmitter<string>();
3.Shared Service: Share data between unrelated components.
- Dynamic Components: Use ViewContainerRef to load components dynamically.
const componentRef = this.viewContainerRef.createComponent(MyComponent);
-
Two-Way Binding: Achieved using
[(ngModel)]
in forms.
<input [(ngModel)]="username" />
3. Directives
- Structural Directives: Modify the DOM structure.
<div *ngIf="isVisible">Visible Content</div>
- Structural Directives (Advanced): Use ng-template to render content dynamically.
<ng-template [ngIf]="isVisible">
<p>Conditionally Visible!</p>
</ng-template>
- Attribute Directives: Modify the appearance or behavior of an element.
<div [ngClass]="{'active': isActive}"></div>
- Custom Structural Directive Example:
@Directive({
selector: '[appUnless]'
})
export class UnlessDirective {
@Input() set appUnless(condition: boolean) {
if (!condition) {
this.vcRef.createEmbeddedView(this.templateRef);
} else {
this.vcRef.clear();
}
}
constructor(private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef) {}
}
4. Modules
Types of Modules
- Root Module: Bootstraps the application.
-
Feature Modules: Contain app features (e.g.,
UserModule
). - Shared Modules: Reusable components and directives.
Example of a Shared Module:
@NgModule({
declarations: [SharedComponent],
exports: [SharedComponent],
imports: [CommonModule]
})
export class SharedModule {}
NgModules structure:
- Declarations: Components, directives, and pipes declared in this module.
- Providers: Register services globally or locally.
- Exports: Components, directives, or pipes made available to other modules.
Imports: Modules needed for functionality.
Lazy Loading Advanced Example:
const routes: Routes = [
{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule) }
];
- Shared Module Best Practices: Always export commonly used components or modules:
@NgModule({
imports: [CommonModule, FormsModule],
declarations: [CustomDirective, CustomPipe],
exports: [CustomDirective, CustomPipe, FormsModule]
})
export class SharedModule {}
5. Services and Dependency Injection
What are Services?
- Services provide reusable logic (e.g., HTTP requests, data sharing).
Example:
@Injectable({ providedIn: 'root' })
export class DataService {
getData() {
return ['Angular', 'React', 'Vue'];
}
}
Dependency Injection
DI allows services to be injected into components.
Hierarchical Dependency Injection:
- Angular creates injectors at each module, component, or service level, allowing flexibility in providing services.
- Controls the scope of a service (global, module, or component level).
@Injectable({ providedIn: 'root' })
export class DataService {}
- DI allows services to be injected into components.
constructor(private dataService: DataService) {}
- Multi-Provider Pattern: Provide multiple implementations for a service.
providers: [{ provide: TOKEN, useClass: Service1 }, { provide: TOKEN, useClass: Service2 }]
6. Routing and Navigation
Basics of Routing
- RouterModule provides navigation between views.
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
Route Parameters
- Pass data via the URL.
{ path: 'user/:id', component: UserComponent }
- Access parameters in the component:
this.route.snapshot.paramMap.get('id');
Guards
- Secure routes using guards like
CanActivate
.
canActivate(): boolean {
return this.authService.isLoggedIn();
}
- Dynamic Route Navigation: Programmatically navigate between routes using the Router service:
this.router.navigate(['/products', productId], { queryParams: { category: 'electronics' } });
7. Forms in Angular
Template-Driven Forms
- Easier to use, suitable for simple forms.
<form #form="ngForm" (ngSubmit)="onSubmit(form.value)">
<input name="username" ngModel required />
</form>
Reactive Forms
- More powerful, used for complex forms.
this.form = new FormGroup({
username: new FormControl('', Validators.required)
});
- Dynamically add/remove form controls.
this.form.addControl('email', new FormControl('', Validators.email));
this.form.removeControl('email');
- Custom Validators: Create reusable validation logic.
static emailDomainValidator(domain: string): ValidatorFn {
return (control: AbstractControl) => {
const email = control.value;
if (email && email.includes(domain)) return null;
return { domainError: true };
};
}
8.Pipes
- Chaining Pipes: Combine multiple pipes
{{ '2024-12-03T10:00:00' | date:'long' | uppercase }}
Pure vs Impure Pipes:
Pure Pipes: Only re-evaluated when input changes.
Impure Pipes: Re-evaluated on every change detection cycle.
Custom Async Pipe: Handle Observables with ease.
transform(obs$: Observable<any>): any {
return obs$.pipe(map(data => data.value));
}
9. RxJS and Observables
What is RxJS?
- RxJS is a library for reactive programming, extensively used in Angular for handling asynchronous events.
Observables
- Observables emit data over time. Use
.subscribe()
to react to emissions.
const observable = new Observable(subscriber => {
subscriber.next('Hello');
subscriber.complete();
});
Operators
- Transform or filter observable data.
this.http.get('url').pipe(
map(data => data.results),
filter(item => item.isActive)
).subscribe();
10. State Management with NgRx
What is NgRx?
- NgRx is a state management library based on Redux principles. It provides predictable state changes.
Key Concepts:
- Actions: Define state changes.
export const addUser = createAction('[User] Add User', props<{ user: User }>());
- Reducers: Handle state transitions.
const userReducer = createReducer(
initialState,
on(addUser, (state, { user }) => [...state, user])
);
- Selectors: Retrieve state slices.
const selectUsers = createSelector(selectAppState, state => state.users);
11. Performance Optimization
Change Detection
- How Change Detection Works: Angular uses Zone.js to track asynchronous operations like Promises or HTTP requests and trigger the change detection cycle.
- Default: Re-renders the entire component tree. Re-renders the entire tree when any change is detected.
OnPush: Renders only when inputs change. Updates the DOM only if input properties are mutated or events are fired.
Optimize with Immutability:
Use immutability to detect changes efficiently in OnPush.
@Input() data = { name: 'John' }; // Avoid mutation!
Lazy Loading
Load modules only when needed to reduce the initial bundle size.
Lazy Loading with Route Components:
Use component directly without separate modules.
{ path: 'user', component: () => import('./user.component').then(c => c.UserComponent) }
Bundle Splitting: Divide JavaScript bundles using Webpack for faster initial loading.
Preloading Strategy: Load critical resources in the background.
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules });
Tree Shaking
- Removes unused code during build.
*12.Latest Angular Features *
- Signal API (16): Replace Observables for state management.
const counter = signal(0);
const double = computed(() => counter() * 2);
Environment Variables (19):
Enhanced support for managing configurations for dev, staging, and prod.Control Flow (@if):
Cleaner conditional rendering:
@if (isLoggedIn) {
<p>Welcome back!</p>
}
- Standalone APIs: No need for NgModules for every feature:
bootstrapApplication(AppComponent);
SUMMERIZE:
1. Angular Basics
What is Angular?
A TypeScript-based, open-source framework for building dynamic single-page applications (SPAs). It emphasizes a component-based architecture.-
Core Features:
- Modular architecture using NgModules.
- Dependency Injection (DI).
- Reactive programming with RxJS.
- Ahead-of-Time (AOT) compilation for performance optimization.
2. Components
- Definition: The UI building blocks of an Angular application.
-
Structure:
- HTML Template: Defines the structure of the view.
- CSS/SCSS: For styling.
- TypeScript Class: Contains logic and data-binding definitions.
-
Lifecycle Hooks:
-
ngOnInit
: Executes after the component is initialized. -
ngOnChanges
: Executes on input property changes. -
ngAfterViewInit
: Executes after child views are initialized. -
ngOnDestroy
: Used for cleanup (e.g., unsubscribing Observables).
-
3. Directives
- What are Directives? Instructions to the DOM.
-
Types:
-
Structural Directives: Modify the DOM layout.
-
*ngIf
: Conditionally add/remove elements. -
*ngFor
: Loop through data and render elements.
-
-
Attribute Directives: Modify element appearance or behavior.
-
ngClass
: Add/remove CSS classes dynamically. -
ngStyle
: Apply styles dynamically.
-
-
Custom Directives: Extend Angular's behavior using
@Directive
.
-
Structural Directives: Modify the DOM layout.
4. Data Binding
-
Binding Types:
-
Interpolation: Embed dynamic values in templates (
{{ value }}
). -
Property Binding:
[property]="expression"
. -
Event Binding:
(event)="function($event)"
. -
Two-Way Binding:
[(ngModel)]="property"
(requiresFormsModule
).
-
Interpolation: Embed dynamic values in templates (
5. Modules
- What are Modules? Logical containers for organizing an application.
-
Common Modules:
- AppModule: Root module.
-
Feature Modules: For specific features (e.g.,
UserModule
). - Shared Modules: For shared components, directives, and pipes.
- Lazy Modules: Load on demand for better performance.
6. Routing and Navigation
- RouterModule: Configures routes for navigation.
-
Features:
-
Guards: Protect routes (
CanActivate
,CanLoad
). -
Lazy Loading: Use
loadChildren
for dynamic module loading. -
Optional Parameters: Pass additional data (
path: 'details/:id?name='
). - Route Resolvers: Pre-fetch data before navigating.
-
Guards: Protect routes (
7. Forms
-
Template-Driven Forms:
- Requires
FormsModule
. - Simpler but less scalable.
- Example:
<input [(ngModel)]="userName" name="userName" required />
- Requires
-
Reactive Forms:
- Requires
ReactiveFormsModule
. - Uses
FormGroup
andFormControl
for a more structured approach. - Example:
this.form = new FormGroup({ name: new FormControl(''), });
- Requires
8. Angular CLI
- Automates project setup, building, and optimization tasks.
-
Useful Commands:
-
ng new
: Create a new Angular project. -
ng serve
: Start a development server. -
ng generate
: Scaffold components, services, etc.
-
9. Dependency Injection
- Definition: A design pattern that injects services into components.
- Hierarchical Injector: Services provided at different levels (module, component).
-
Singleton Service: Provided in
root
to make it application-wide.
10. Advanced Features
- AOT Compilation: Pre-compiles templates and TypeScript for faster load times.
- Tree Shaking: Removes unused code during the build process.
-
Change Detection Strategies:
- Default: Checks the whole component tree.
- OnPush: Checks only when input properties change.
- RxJS: Reactive Extensions for handling asynchronous data streams.
11. Latest Concepts (Angular 16-19)
-
Standalone Components (Angular 14):
Components can exist without being part of a module using
standalone: true
. - Signal API (Angular 16): A new reactivity model for state management.
import { signal } from '@angular/core';
const counter = signal(0);
- ESBuild (Angular 15): Faster builds using ESBuild by default.
-
Improved Control Flow (Angular 16):
- New control-flow syntax like
@if
,@for
for better template readability.
- New control-flow syntax like
- Typed Forms (Angular 14): Strong typing for form controls and groups.
- Environment Variables (Angular 19): Enhanced support for managing multiple environment variables.
- Server-Side Rendering (Angular Universal): Better hydration support and APIs.
12. Pipes
-
Built-in Pipes:
date
,currency
,percent
, etc. -
Custom Pipes: Use
@Pipe
to transform data.
This detailed roadmap combines foundational knowledge with advanced topics to ensure you’re prepared for any Angular interview. The references linked provide more depth and real-world examples. Let me know if you need further details on any section!
Top comments (0)