Component – Angular

In Angular, a component is the core building block of the user interface. Every Angular application is a tree of components that define the view (what the user sees) and manage the logic (how the application behaves). Components are essential to developing modular, reusable, and scalable applications in Angular.

Each Angular component consists of four key parts:

  1. A Class (which handles logic and data).
  2. An HTML Template (which defines the view).
  3. CSS Styles (which define the look and feel of the component).
  4. Metadata (which tells Angular how to handle the component).

1. Component Structure

A component is defined by a TypeScript class that is decorated with the @Component decorator. This decorator provides metadata about the component, such as the selector (used to embed the component in templates), the template URL (or inline template), and styles for that component.

Here’s a simple example of a component:

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

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class MyComponent {
  title: string = 'Hello Angular';
  constructor() {}

  onClick(): void {
    console.log('Button clicked!');
  }
}

In this example:

  • Selector: 'app-my-component' is the tag used to represent the component in the template (<app-my-component></app-my-component>).
  • Template: The templateUrl points to an external HTML file (my-component.component.html) that contains the view for the component.
  • Styles: The styleUrls point to a CSS file (my-component.component.css) that contains styles specific to this component.
  • Class: The class MyComponent holds the logic, properties, and methods that define the behavior of the component.

2. Component Decorator (@Component)

The @Component decorator is used to configure the component and provide metadata. Here are the key properties of the @Component decorator:

  • selector: Defines the custom HTML tag that represents the component.
  • Example: selector: 'app-my-component' allows you to use <app-my-component></app-my-component> in other templates.
  • template or templateUrl: Defines the HTML template for the component.
  • template: Inline HTML template (used for small components).
  • templateUrl: Reference to an external HTML file (used for larger templates).
  • styleUrls or styles: Defines the styles for the component.
  • styles: Inline CSS (for small, simple styles).
  • styleUrls: Reference to an external CSS file(s).
  • providers: Defines services available to the component and its children via Dependency Injection.
  • animations: Defines animations that the component will use.

3. Component Lifecycle

Each Angular component has a lifecycle, which is a series of methods that Angular calls at specific stages of a component’s creation, update, and destruction. You can hook into these lifecycle methods to add custom logic for initialization, change detection, and cleanup.

Here are the important lifecycle hooks for a component:

  • ngOnInit(): Called after the component is initialized (useful for initializing component properties).
  • ngOnChanges(): Called when any data-bound input property changes.
  • ngDoCheck(): Called during every change detection run.
  • ngAfterContentInit(): Called after content (ng-content) has been projected into the view.
  • ngAfterContentChecked(): Called after projected content is checked.
  • ngAfterViewInit(): Called after the component’s view and its child views have been initialized.
  • ngAfterViewChecked(): Called after the component’s view and its child views have been checked.
  • ngOnDestroy(): Called just before the component is destroyed (useful for cleanup tasks).

Example:

export class MyComponent implements OnInit {
  title: string;

  ngOnInit() {
    // Logic to initialize component data
    this.title = 'Welcome to Angular!';
  }

  ngOnDestroy() {
    // Logic to clean up resources
    console.log('Component is being destroyed');
  }
}

4. Component Interaction

Components often need to communicate with each other, either by passing data from a parent to a child or sending events from a child back to a parent.

a) Input Binding

  • @Input() is used to pass data from a parent component to a child component.

Example:

// Child Component (my-child.component.ts)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-my-child',
  template: `<p>{{ message }}</p>`
})
export class MyChildComponent {
  @Input() message: string;
}

// Parent Component (app.component.html)
<app-my-child [message]="parentMessage"></app-my-child>

In this example, the parent component passes the value of parentMessage to the message property of the child component.

b) Output Binding

  • @Output() and EventEmitter are used to send events from a child component to a parent component.

Example:

// Child Component (my-child.component.ts)
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-my-child',
  template: `<button (click)="sendMessage()">Click me</button>`
})
export class MyChildComponent {
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Hello from Child Component!');
  }
}

// Parent Component (app.component.html)
<app-my-child (messageEvent)="receiveMessage($event)"></app-my-child>

In this example, the child component emits an event (messageEvent) that the parent component listens for and handles (receiveMessage($event)).


5. Data Binding in Components

Angular provides several types of data binding to handle interactions between the component class and the template:

a) Interpolation ({{}})

Interpolation is used to bind data from the component class to the template.

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

b) Property Binding ([])

Property binding allows you to bind data from the component to HTML element properties.

<img [src]="imageUrl" />

c) Event Binding (())

Event binding is used to listen for DOM events and call methods in the component class.

<button (click)="onClick()">Click me</button>

d) Two-Way Data Binding ([()])

Two-way data binding allows you to synchronize data between the view and the component class using the ngModel directive.

<input [(ngModel)]="username" />

6. Templates in Components

Components have associated templates that define the UI structure. You can define templates inline or by referencing external HTML files.

a) Inline Template

@Component({
  selector: 'app-inline-template',
  template: `<h1>Hello, Inline Template!</h1>`,
})
export class InlineTemplateComponent {}

b) External Template

@Component({
  selector: 'app-external-template',
  templateUrl: './external-template.component.html',
})
export class ExternalTemplateComponent {}

Example External Template (external-template.component.html):

<h1>{{ title }}</h1>
<p>This is an external template.</p>

7. Styles in Components

Angular components can have their own CSS styles, which can be scoped to the component to avoid conflicts with other styles in the application.

a) Inline Styles

@Component({
  selector: 'app-inline-styles',
  template: `<p>Styled text</p>`,
  styles: [`p { color: blue; }`]
})
export class InlineStylesComponent {}

b) External Styles

@Component({
  selector: 'app-external-styles',
  templateUrl: './external-styles.component.html',
  styleUrls: ['./external-styles.component.css']
})
export class ExternalStylesComponent {}

Example External CSS (external-styles.component.css):

p {
  font-size: 18px;
  color: green;
}

8. Component Module Integration

Components are typically declared inside an Angular Module (NgModule). To use a component, you must declare it in the declarations array of a module. Here’s how to declare a component in a module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MyComponent } from './my-component/my-component.component';

@NgModule({
  declarations: [
    AppComponent,
    MyComponent
  ],
  imports: [
    BrowserModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Conclusion

Angular components are essential building blocks of an Angular application. They define the view, encapsulate behavior and logic, and interact with other components and services. By using components, Angular promotes a modular, reusable, and maintainable architecture. Components also make it easier to structure and organize complex applications into manageable pieces.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *