In Angular, the Document Object Model (DOM) is the structure of the HTML elements that make up your Angular application.
Angular provides a way to interact with and manipulate the DOM through templates, components, directives, and services.
Here's how Angular interacts with the DOM:
Angular components use templates to define the structure of the DOM.
Templates are written in HTML with additional Angular-specific syntax for data binding, directives, and structural directives. Angular compiler processes templates and generates corresponding DOM elements.
<!-- app.component.html --> <h1>{{ title }}</h1> <button (click)="onButtonClick()">Click me</button>
Angular provides various types of data binding to connect the component class with the template and update the DOM dynamically.
"{{ expression }}" - Updates the DOM with the value of the expression based on component data changes and user interactions.
[property]="expression" - Property binding techniques used to bind value with the property of an HTML element in the DOM based on component data changes and user interactions.
(event)="expression" - Listens to events triggered by the HTML elements and executes an expression in the component class.
[(ngModel)]="property" - Combines property binding and event binding to achieve two-way data binding.
<!-- app.component.html --> <input type="text" [value]="name" (input)="name = $event.target.value">
Directives are a way to extend HTML with custom behaviour or apply special attributes to DOM elements.
Angular directives are used to add behaviour or manipulate the DOM. Directives can be structural or attribute directives.
Modify the structure of the DOM by adding or removing elements based on conditions.
*ngIf: Conditionally adds or removes an element from the DOM.
*ngFor: Loops over a collection and generates multiple elements.
Modify the appearance or behaviour of an existing element.
[ngStyle]: Binds the style properties of an element to expressions.
[ngClass]: Binds CSS classes to elements dynamically.
Angular provides mechanisms to access and manipulate the DOM directly when necessary, although it encourages a declarative approach through templates and data binding.
Angular lifecycle hooks provide opportunities to perform actions in various stages of a component's lifecycle.
These hooks allow us to perform tasks such as accessing the DOM after it has been rendered (ngAfterViewInit) or cleaning up resources before a component is destroyed (ngOnDestroy).