Angular : Basic Concepts

Angular is built on a set of fundamental concepts that allow developers to create dynamic and scalable web applications. This blog explores key Angular basics, including components, directives, data binding, and lifecycle hooks.

1. Components and Templates

In Angular, components are the building blocks of any application. They define the view and behavior of your app. A component is essentially a TypeScript class that is associated with a template (HTML) to define its structure and layout.

Components

  • A TypeScript file: Contains the logic and data for the component (e.g., app.component.ts).
  • An HTML template: Defines how the component is rendered in the UI.
  • A CSS file (optional): Adds styles specific to the component.

To create a new component in an Angular project using the Angular CLI, we use this command :


ng generate component <component-name>
  

Here’s an example of a basic Angular component:


    ng generate component example;
      

example.component.ts :

import { Component } from '@angular/core';

@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
title = 'Welcome to Angular!';
}
      

In this example:

  • selector: Represents the HTML tag to use for this component (<app-example>).
  • templateUrl: Points to the associated HTML file.
  • styleUrls: Specifies optional CSS styles for the component.

example.component.html :


      <p>{{title}}</p>

      


2. Directives: Structural vs. Attribute

Angular directives are special markers in the DOM that extend HTML’s capabilities by modifying elements or adding behaviors.

Types of Directives

1. Structural Directives

Structural directives modify the DOM layout by adding or removing elements. Common examples include:

  • *ngIf: Conditionally displays an element.
    <div *ngIf="isVisible">This is visible!</div>
                  


  • *ngFor: Iterates over a collection and creates elements for each item.
    <ul>
    <li *ngFor="let item of items">{{ item }}</li>
    </ul>
                  


2. Attribute Directives

Attribute directives change the appearance or behavior of an element. Examples include:

  • ngClass: Dynamically applies classes.
    <div [ngClass]="{'active': isActive, 'inactive': !isActive}">Status</div>
                  



  • ngStyle: Applies inline styles dynamically.
    <div [ngStyle]="{'color': textColor, 'font-size': fontSize}">Styled Text</div>
                  

3. Data Binding

Angular's data binding allows seamless communication between the component and its template. It keeps the data and UI in sync, enhancing interactivity.

Types of Data Binding

  • Interpolation: Used to display data from the component in the template. Syntax: {{ data }}
    <h1>{{ title }}</h1>
                  
  • Property Binding: Binds a property in the template to a field in the component.
    <img [src]="imageUrl" />
                  
  • Event Binding: Listens for events like clicks and binds them to component methods.
    <button (click)="onClick()">Click Me</button>
                  
  • Two-Way Binding: Combines property and event binding for seamless data flow.
    <input [(ngModel)]="username" />
    <p>Hello, {{ username }}!</p>
                  

    Note: To use ngModel, you must import the FormsModule in your Angular module.

4. Component Lifecycle Hooks

Every Angular component goes through a lifecycle, from creation to destruction. Angular provides lifecycle hooks to let you tap into key moments.

Common Lifecycle Hooks

  • ngOnInit: Triggered after the component is initialized.
    ngOnInit() {
    console.log('Component initialized!');
    }
                  
  • ngOnChanges: Called whenever input properties change.
    ngOnChanges(changes: SimpleChanges) {
    console.log('Changes detected:', changes);
    }
                  
  • ngAfterViewInit: Invoked after the component’s view has been fully initialized.
    ngAfterViewInit() {
    console.log('View initialized!');
    }
                  
  • ngOnDestroy: Called just before the component is destroyed.
    ngOnDestroy() {
    console.log('Component destroyed!');
    }
                  

Here is a diagram that presents all lifecycle hooks and a description for each hook :

Lifecycle Hook Description
ngOnChanges

Called whenever one or more data-bound input properties change. The hook receives a SimpleChanges object with current and previous property values.

ngOnInit

Called once, after the first ngOnChanges. This is where you can perform component initialization logic.

ngDoCheck

Called during every change detection run, allowing you to implement custom change detection. Use with caution as it may impact performance.

ngAfterContentInit

Called once after Angular has fully initialized all content projected into the component's view using <ng-content>.

ngAfterContentChecked

Called after every check of projected content. Useful for responding to changes in the projected content.

ngAfterViewInit

Called once after Angular has initialized the component's view and any child views. Use this hook for view-related initialization.

ngAfterViewChecked

Called after every check of the component's view and child views. Useful for responding to changes in the view.

ngOnDestroy

Called just before Angular destroys the component. Use this hook to clean up resources, unsubscribe from Observables, and prevent memory leaks.

Conclusion

Understanding the basic concepts of Angular is essential for building dynamic and scalable web applications. By mastering components, directives, data binding, and lifecycle hooks, you can effectively create interactive and maintainable applications. Dive deeper into these concepts, and you'll unlock the full potential of Angular in no time!

Post a Comment

0 Comments