Sobes.tech
Middle

How does Angular work?

sobes.tech AI

Answer from AI

Angular is based on the MVC/MVVM architecture. It uses components, data binding, and dependency injection to build interactive web applications.

Main concepts:

  • Components: Building blocks of the application, consisting of a template, class, and styles.
  • Modules (NgModules): Group related components, services, and other elements.
  • Data Binding: Synchronizes data between the model and the view.
    • One-way binding: Data flows in one direction (e.g., from model to view).
    • Two-way binding [()]: Changes in the model affect the view and vice versa.
  • Services: Provide functionality that can be used by different components (e.g., working with HTTP requests).
  • Dependency Injection (DI): Mechanism for providing dependencies (e.g., services) to components.
  • Templates: HTML with Angular syntax extensions for displaying data and handling events.
  • Directives: Change the behavior or appearance of DOM elements.
    • Structural: Add, remove, or manipulate DOM elements (e.g., *ngIf, *ngFor).
    • Attribute: Change the appearance or behavior of existing elements (e.g., [ngClass], [ngStyle]).
  • Component Lifecycle: Set of hooks that allow executing code at various stages of a component's life (e.g., OnInit, OnDestroy).
  • Zones (NgZone): Provide automatic change detection and view update during asynchronous operations.

Workflow:

  1. Loading: The application loads, the Bootstrap module launches the root component.
  2. Rendering: Angular compiles templates and creates the DOM structure.
  3. Data Binding: Establishes a connection between data and view.
  4. Event Handling: Event listeners respond to user actions.
  5. Change Detection: Zone tracks asynchronous operations.
  6. View Update: When changes are detected, Angular updates the relevant parts of the DOM.

Example of two-way data binding:

<!-- In the template -->
<input [(ngModel)]="userName">
<p>Hello, {{ userName }}!</p>
// In the component class
export class MyComponent {
  userName: string = '';
}