DEV Community

Renuka Patil
Renuka Patil

Posted on • Edited on

9 3 3 3 2

Last-Minute Angular Notes

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';
  }
Enter fullscreen mode Exit fullscreen mode
  • *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>
    
    • Two-Way Binding: Achieved using [(ngModel)] in forms.
     <input [(ngModel)]="username" />
    
  • Component Communication:

1.Parent to Child: Using @Input properties.

@Input() data: string;
Enter fullscreen mode Exit fullscreen mode

2.Child to Parent: Using @Output with EventEmitter.

@Output() notify = new EventEmitter<string>();
Enter fullscreen mode Exit fullscreen mode

3.Shared Service: Share data between unrelated components.

  • Dynamic Components: Use ViewContainerRef to load components dynamically.
const componentRef = this.viewContainerRef.createComponent(MyComponent);

Enter fullscreen mode Exit fullscreen mode

3. Directives

  • Structural Directives: Modify the DOM structure.
  <div *ngIf="isVisible">Visible Content</div>
Enter fullscreen mode Exit fullscreen mode
  • Structural Directives (Advanced): Use ng-template to render content dynamically.
<ng-template [ngIf]="isVisible">
  <p>Conditionally Visible!</p>
</ng-template>

Enter fullscreen mode Exit fullscreen mode
  • Attribute Directives: Modify the appearance or behavior of an element.
  <div [ngClass]="{'active': isActive}"></div>
Enter fullscreen mode Exit fullscreen mode
  • 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) {}
}

Enter fullscreen mode Exit fullscreen mode

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 {}
Enter fullscreen mode Exit fullscreen mode

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) }
];

Enter fullscreen mode Exit fullscreen mode
  • 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 {}
Enter fullscreen mode Exit fullscreen mode

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'];
  }
}
Enter fullscreen mode Exit fullscreen mode

Dependency Injection

  • DI allows services to be injected into components.

  • Hierarchical Dependency Injection:

  1. Angular creates injectors at each module, component, or service level, allowing flexibility in providing services.
  2. Controls the scope of a service (global, module, or component level).
@Injectable({ providedIn: 'root' })
export class DataService {}
Enter fullscreen mode Exit fullscreen mode
  • DI allows services to be injected into components.
  constructor(private dataService: DataService) {}
Enter fullscreen mode Exit fullscreen mode
  • Multi-Provider Pattern: Provide multiple implementations for a service.
providers: [{ provide: TOKEN, useClass: Service1 }, { provide: TOKEN, useClass: Service2 }]

Enter fullscreen mode Exit fullscreen mode

6. Routing and Navigation

Basics of Routing

  • RouterModule provides navigation between views.
  const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: 'about', component: AboutComponent }
  ];
Enter fullscreen mode Exit fullscreen mode

Route Parameters

  • Pass data via the URL.
  { path: 'user/:id', component: UserComponent }
Enter fullscreen mode Exit fullscreen mode
  • Access parameters in the component:
  this.route.snapshot.paramMap.get('id');
Enter fullscreen mode Exit fullscreen mode

Guards

  • Secure routes using guards like CanActivate.
  canActivate(): boolean {
    return this.authService.isLoggedIn();
  }
Enter fullscreen mode Exit fullscreen mode
  • Dynamic Route Navigation: Programmatically navigate between routes using the Router service:
this.router.navigate(['/products', productId], { queryParams: { category: 'electronics' } });

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Reactive Forms

  • More powerful, used for complex forms.
  this.form = new FormGroup({
    username: new FormControl('', Validators.required)
  });
Enter fullscreen mode Exit fullscreen mode
  • Dynamically add/remove form controls.
this.form.addControl('email', new FormControl('', Validators.email));
this.form.removeControl('email');

Enter fullscreen mode Exit fullscreen mode
  • 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 };
  };
}

Enter fullscreen mode Exit fullscreen mode

8.Pipes

  • Chaining Pipes: Combine multiple pipes
{{ '2024-12-03T10:00:00' | date:'long' | uppercase }}

Enter fullscreen mode Exit fullscreen mode
  • 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));
}

Enter fullscreen mode Exit fullscreen mode

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();
  });
Enter fullscreen mode Exit fullscreen mode

Operators

  • Transform or filter observable data.
  this.http.get('url').pipe(
    map(data => data.results),
    filter(item => item.isActive)
  ).subscribe();
Enter fullscreen mode Exit fullscreen mode

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 }>());
Enter fullscreen mode Exit fullscreen mode
  • Reducers: Handle state transitions.
  const userReducer = createReducer(
    initialState,
    on(addUser, (state, { user }) => [...state, user])
  );
Enter fullscreen mode Exit fullscreen mode
  • Selectors: Retrieve state slices.
  const selectUsers = createSelector(selectAppState, state => state.users);
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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) }

Enter fullscreen mode Exit fullscreen mode
  • Bundle Splitting: Divide JavaScript bundles using Webpack for faster initial loading.

  • Preloading Strategy: Load critical resources in the background.

RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules });
Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode
  • 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>
}

Enter fullscreen mode Exit fullscreen mode
  • Standalone APIs: No need for NgModules for every feature:
bootstrapApplication(AppComponent);

Enter fullscreen mode Exit fullscreen mode

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:
    1. Structural Directives: Modify the DOM layout.
      • *ngIf: Conditionally add/remove elements.
      • *ngFor: Loop through data and render elements.
    2. Attribute Directives: Modify element appearance or behavior.
      • ngClass: Add/remove CSS classes dynamically.
      • ngStyle: Apply styles dynamically.
    3. Custom Directives: Extend Angular's behavior using @Directive.

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" (requires FormsModule).

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.

7. Forms

  • Template-Driven Forms:

    • Requires FormsModule.
    • Simpler but less scalable.
    • Example:
    <input [(ngModel)]="userName" name="userName" required />
    
  • Reactive Forms:

    • Requires ReactiveFormsModule.
    • Uses FormGroup and FormControl for a more structured approach.
    • Example:
    this.form = new FormGroup({
      name: new FormControl(''),
    });
    

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);
Enter fullscreen mode Exit fullscreen mode
  • 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.
  • 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!

Check this blog: Comprehensive Angular Interview Questions and Answers🚀

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay