Frontend Development (Angular) Flashcards
What is the difference between Angular and React?
- Angular: A full-fledged MVC framework developed by Google, using TypeScript.
- React: A UI library developed by Facebook, using JavaScript/JSX.
- Key Differences:
Feature Angular React
Architecture Full Framework (MVC) Library (View Layer)
Language TypeScript JavaScript (JSX)
State Management Services, NgRx React Context, Redux
Performance Heavier due to two-way binding Faster due to Virtual DOM
Learning Curve Steeper Easier
What are the advantages of using Angular?
- Two-way Data Binding: Automatically synchronizes data between the model and the view.
- Dependency Injection: Provides better modularity and testability.
- Modular Architecture: Applications are split into reusable modules.
- Directives & Pipes: Reusable components that simplify UI logic.
- Built-in Security: Prevents XSS and CSRF attacks.
What is Change Detection in Angular?
- Change Detection determines when and how the UI should update when data changes.
- Angular uses Zone.js to detect changes automatically.
- Change Detection Strategies:
o Default: Checks all components (more resource-intensive).
o OnPush: Checks only when inputs change (better performance).
What are Angular Directives?
- Directives modify HTML elements dynamically.
- Types of Directives:
1. Structural Directives (*ngIf, *ngFor, *ngSwitch) → Modify DOM structure.
2. Attribute Directives (ngClass, ngStyle) → Change appearance/behavior.
3. Custom Directives → User-defined directives for reusability.
What are Angular Services? How are they different from Components?
- Services:
o Provide reusable logic (e.g., API calls, authentication, caching).
o Created with @Injectable() and used via Dependency Injection. - Components:
o Define UI and contain the HTML, CSS, and logic.
o Cannot be shared easily like services.
What is Lazy Loading in Angular? Why is it useful?
- Lazy Loading loads modules only when needed, reducing the initial bundle size.
- Advantages:
o Improves application performance & load time.
o Reduces memory consumption.
o Prevents unnecessary code execution. - Implementation Example:
- const routes: Routes = [
- { path: ‘dashboard’, loadChildren: () => import(‘./dashboard.module’).then(m => m.DashboardModule) }
What is RxJS, and why is it used in Angular?
- RxJS (Reactive Extensions for JavaScript) is a library for handling asynchronous operations.
- Angular uses RxJS for:
o Handling HTTP requests with HttpClient.
o Event handling with Observables.
o State management (NgRx uses RxJS).
What is the difference between Promises and Observables?
Feature Promise Observable
Execution Eager (executes immediately) Lazy (executes when subscribed)
Multiple Values No (Resolves once) Yes (Emits multiple values over time)
Cancellation Not possible Can be canceled
Operators Limited (then, catch) Rich (map, filter, debounce)
: What is NgRx? How does it work?
- NgRx is a state management library for Angular using Redux principles.
- Key Concepts:
1. Store – Centralized state management.
2. Actions – Define events that trigger state changes.
3. Reducers – Pure functions that update the state.
4. Effects – Handle side effects like HTTP requests.
What are Angular Pipes?
- Pipes format data dynamically in templates.
- Built-in Pipes: uppercase, date, currency.
- Custom Pipe Example:
- @Pipe({ name: ‘reverse’ })
- export class ReversePipe implements PipeTransform {
- transform(value: string): string {
- return value.split(‘’).reverse().join(‘’);
- }
What are Web Components, and how does Angular support them?
- Web Components are reusable, framework-independent UI elements.
- Angular Elements allows creating Web Components using Angular.
- Example:
- @Component({ selector: ‘custom-button’, template: ‘<button>{{label}}</button>’ })
What are Content Projection and ViewEncapsulation in Angular?
- Content Projection (<ng-content>) allows inserting external HTML into a component.</ng-content>
- ViewEncapsulation controls how styles are applied:
o Emulated (Default): Styles are scoped.
o None: Styles are global.
o ShadowDom: Uses native Shadow DOM.
How does Angular handle security vulnerabilities?
: Angular provides built-in security mechanisms to protect applications against common web vulnerabilities such as XSS (Cross-Site Scripting), CSRF (Cross-Site Request Forgery), and Clickjacking. It enforces security through automatic HTML sanitization, content security policies, and HTTP security features.
What is Cross-Site Scripting (XSS) in Angular, and how do you prevent it
- XSS occurs when an attacker injects malicious scripts into web applications to steal user data, hijack sessions, or execute unauthorized actions.
- How Angular Prevents XSS:
1. Automatic Sanitization: Angular escapes and sanitizes user-generated content in the template by default.
2. Bypass Security Risks: If necessary, Angular provides DomSanitizer to explicitly trust safe content.
3. Example:
4. import { DomSanitizer } from ‘@angular/platform-browser’;
5.
6. constructor(private sanitizer: DomSanitizer) {}
7.
this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(‘<h1>Safe Content</h1>’);
How does Angular handle Content Security Policy (CSP)?
- CSP helps prevent XSS attacks by restricting the sources from which content can be loaded.
- To configure CSP: Modify the HTTP headers to allow only trusted sources.
- Example CSP Header:
Content-Security-Policy: default-src ‘self’; script-src ‘self’ ‘unsafe-inline’;
What is Clickjacking, and how do you prevent it in Angular?
- Clickjacking occurs when an attacker embeds an application inside an iframe to trick users into clicking on elements unknowingly.
- Prevention Techniques:
1. Use X-Frame-Options header: Set DENY or SAMEORIGIN to block iframe embedding.
2. Use Content Security Policy (CSP) frame-ancestors directive:
Content-Security-Policy: frame-ancestors ‘none’;
What is Angular’s Trusted Types Policy?
- Trusted Types prevent DOM-based XSS attacks by enforcing strict content validation before inserting dynamic content into the DOM.
- Angular uses DomSanitizer and trusted types APIs to enforce safe content insertion.
: How do you securely handle authentication and authorization in Angular?
- Use OAuth2 or OpenID Connect with JWT (JSON Web Tokens) for authentication.
- Store JWT tokens securely using HttpOnly cookies instead of local storage.
- Implement route guards (CanActivate) to restrict access based on user roles.
- Use Angular Interceptors to attach authentication headers automatically.
- export class AuthInterceptor implements HttpInterceptor {
- intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {</any></any>
- const clonedReq = req.clone({
- setHeaders: { Authorization:
Bearer ${localStorage.getItem('token')}
} - });
- return next.handle(clonedReq);
- }
What are Angular Route Guards, and how do they enhance security?
- Angular Route Guards prevent unauthorized access to routes.
- Types of Route Guards:
o CanActivate: Prevents navigation if conditions aren’t met.
o CanDeactivate: Ensures the user confirms before leaving a page.
o CanLoad: Restricts module loading based on conditions. - Example Implementation:
- @Injectable({ providedIn: ‘root’ })
- export class AuthGuard implements CanActivate {
- constructor(private authService: AuthService, private router: Router) {}
- canActivate(): boolean {
- if (this.authService.isAuthenticated()) {
- return true;
- }
- this.router.navigate([‘/login’]);
- return false;
- }
}
How do you prevent insecure deserialization attacks in Angular?
- Ensure that user-supplied data is not directly parsed into objects.
- Validate and sanitize JSON responses before processing.
- Use TypeScript interfaces to define expected data structures.
- Example:
- interface User {
- id: number;
- name: string;
- }
- fetchUser(): Observable<User> {</User>
- return this.http.get<User>('/api/user');
}</User>
What are some best practices for securing an Angular application?
- Use HTTPS to encrypt data transmission.
- Sanitize all user inputs to prevent XSS.
- Implement strict Content Security Policies (CSP).
- Use Angular’s built-in security mechanisms (DomSanitizer).
- Avoid using eval() or dynamic script execution.
- Keep Angular and dependencies up to date to patch security vulnerabilities.
How does Angular handle dependency injection?
Angular provides hierarchical dependency injection, meaning services are shared within specific modules or components. The injector tree ensures efficient resource management and prevents unnecessary instantiation of services.
If a component requires a dependency, Angular first looks for it in the element injector of the component. If it isn’t defined in the providers array, then the framework looks at the parent component. This process repeats for as long as Angular finds a dependency in an ancestor.
Explain RxJS and its role in Angular.
RxJS (Reactive Extensions for JavaScript) is a library for handling asynchronous data streams. It is commonly used in Angular for:
* HTTP requests (HttpClient returns Observables instead of Promises).
* Event handling with reactive programming.
* State management (BehaviorSubject for shared state).
What is lazy loading in Angular?
Lazy loading helps improve performance by loading modules only when they are needed. This reduces initial load time and enhances application efficiency.