In Angular, components serve as the primary building blocks for organizing and managing the application's UI and behaviour.
In earlier versions of AngularJS (Angular 1.x), controllers were used to define the behaviour of different parts of the application.
However, with Angular's transition to a component-based architecture, controllers have been replaced by components.
Here's a comparison between controllers in AngularJS and components in Angular:
In AngularJS, controllers are JavaScript functions that are responsible for defining the behaviour of a particular section of the UI.
They are typically associated with HTML elements or directives in the template.
Controllers are defined using the controller function and are registered with the Angular module.
Controllers can manipulate the scope (data) and interact with services to handle business logic.
angular.module('myApp').controller('MyController', function($scope) { $scope.message = 'Hello, AngularJS!'; });
A component in Angular is a TypeScript class decorated with the @Component decorator, along with a template and optional styles.
Components represent reusable UI elements, such as buttons, forms, navigation bars, or entire sections of a web page.
A typical Angular component consists of four main parts:
Class: Defines the component's properties, methods, and behaviour.
Template: Defines the component's HTML structure and layout.
Metadata: Configures the component's behaviour and metadata using decorators such as @Component.
Styles: Optional CSS styles or preprocessor files (e.g., SCSS) for styling the component.
Angular provides a set of lifecycle hooks that allow you to tap into key moments in a component's lifecycle, such as creation, rendering, updates, and destruction.
Lifecycle hooks include methods like ngOnInit, ngOnChanges, ngAfterViewInit, ngOnDestroy, etc., which are called at specific stages of the component's lifecycle.
import { Component } from '@angular/core'; @Component({ selector: 'your-app', template: `<div> <p>{{ message }}</p> <button (click)="handleClick()">Raise Alert</button> </div>` }) export class YourComponent { message: string = 'Hello, Angular!'; constructor() { } // Method to handle button click event handleClick(): void { alert('Alert has been raised on clicked!'); } }
AngularJS applications often use controllers to manage the application's behaviour and state. However, when migrating to Angular, controllers are replaced by components.
Components offer a more structured and modular way to organize the application's UI and behaviour.
During migration, AngularJS controllers can be converted to Angular components gradually, starting with small parts of the application and moving towards a fully component-based architecture.