Open In App

Introduction To Components And Templates in Angular

Last Updated : 17 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Angular is a powerful framework for building dynamic, single-page web applications. One of the core concepts that make Angular so effective is its use of components and templates. Components and templates are the building blocks of any Angular application, allowing developers to create reusable, maintainable, and interactive UI elements.

In this article, we will dive deep into the fundamentals of Angular components and templates, explore their structure and functionality, and learn how to use them effectively to build robust Angular applications.

What Are Components in Angular?

Components are the fundamental building blocks of Angular applications. A component controls a patch of the screen called a view. Each component in Angular encapsulates a part of the user interface, along with the logic that controls the behaviour of that interface. Components are reusable, self-contained units that can be composed together to build complex UIs.

A component in Angular is defined by three key parts:

  • Template: Defines the HTML view for the component.
  • Class: Contains the data and the logic that powers the template.
  • Metadata: Provides additional information to Angular about how the component should be processed and used.

Structure of an Angular Component

To understand the anatomy of an Angular component, let’s break down its structure:

  • Component Decorator: The component decorator @Component is used to define metadata for the component. This metadata tells Angular what template to use, how to style the component, and any other important configuration.
  • Component Class: The component class contains the data, properties, and methods that define the behavior of the component. It interacts with the template and allows dynamic updates to the view.
  • Component Metadata: The metadata provides additional information to Angular about the component, such as the selector (the HTML tag used to embed the component), template URL, and styles.

Example: Basic Structure of an Angular Component

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

@Component({
selector: 'app-hello-world',
template: `
<h1>{{ title }}</h1>
<p>Welcome to Angular Components!</p>
`,
styles: [`
h1 {
color: blue;
}
`]
})
export class HelloWorldComponent {
title = 'Hello, World!';
}
  • @Component Decorator: Specifies that the class is an Angular component.
  • selector: Defines the custom HTML tag <app-hello-world> that Angular recognizes as this component.
  • template: Provides the HTML structure for the component’s view.
  • styles: Applies CSS styles specifically scoped to this component.

What Are Templates in Angular?

Templates are HTML views that Angular uses to render the user interface. A template in Angular is a combination of regular HTML and Angular-specific syntax that allows for dynamic, data-driven content.

Use of Templates:

  • Data Binding: To dynamically display data and interact with the component class.
  • Directives: To manipulate the DOM based on the data and application logic.
  • Pipes: To transform data before displaying it in the view.

Templates are what the users see and interact with, making them an essential part of the component’s function.

Creating a Simple Angular Component and Template

Let’s create a simple Angular component step-by-step using Angular CLI:

Step 1: Generate a New Component:

Use Angular CLI to generate a new component:

ng new my-angular-application
cd my-angular-application

Step 2: Generate a New Component

ng generate component example

Folder Structure

efcr
Folder Structure

Dependencies

"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}

Step 3: Edit the Component Class

Open example.component.ts and define some properties:

JavaScript
// src/app/example/example.component.ts

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

@Component({
    selector: 'app-example',
    standalone: true,
    templateUrl: './example.component.html',
    styleUrls: ['./example.component.css'],
})
export class ExampleComponent {
    title = 'Hello, Angular!';
}
JavaScript
// src/app/app.component.ts

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ExampleComponent } from './example/example.component';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, ExampleComponent],
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'my-angular-application';
}

Step 4: Create the Template:

In example.component.html, use the properties defined in the class:

HTML
<!-- src/app/example/example.component.html -->
 
<h1>{{ title }}</h1>
<p>Welcome to your first standalone Angular component!</p>
HTML
<!-- src/app/app.component.html -->

<h1>Welcome to {{ title }}!</h1>
<app-example></app-example> 
CSS
/* app.component.css */

h1 {
    color: blue;
}
CSS
/* src/app/app.component.css */

h1 {
    text-align: center;
    color: #333;
}

:host {
    display: block;
    padding: 20px;
    background-color: #f5f5f5;
}


To start the application run the following command.

ng serve --open

Output

cdvv
Introduction to components and templates in Angular

Data Binding in Templates

Data binding is a powerful feature of Angular that connects the template (view) to the component class (model). There are several types of data binding in Angular:

Interpolation

Interpolation is used to display dynamic data from the component class in the template.

Example:

<p>{{ name }}</p> <!-- Displays the value of name property -->

Property Binding

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

Example:

<input [value]="name"> <!-- Binds the input value to the name property -->

Event Binding

Event binding lets you respond to user actions like clicks, input changes, and form submissions.

Example:

<button (click)="sayHello()">Click Me</button>

In the component class:

sayHello() {
alert('Hello, Angular!');
}

Two-Way Data Binding

Two-way data binding allows synchronization between the component class and the template using [(ngModel)]. This is often used in form inputs.

Example:

<input [(ngModel)]="name">
<p>{{ name }}</p> <!-- Displays the updated value as user types -->

To use ngModel, you need to import the FormsModule from @angular/forms in your module.

Using Templates with Structural Directives

Structural directives are special types of directives that manipulate the DOM structure by adding, removing, or modifying elements. Common structural directives include:

1. *ngIf: Conditionally includes or excludes elements based on a Boolean expression.

<p *ngIf="isVisible">This text is visible when isVisible is true.</p>

2. *ngFor: Iterates over a list and repeats elements for each item.

<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>

3. *ngSwitch: Displays one element from a set based on a matching expression.

<div [ngSwitch]="role">
<p *ngSwitchCase="'admin'">Welcome, Admin!</p>
<p *ngSwitchCase="'user'">Welcome, User!</p>
<p *ngSwitchDefault>Welcome, Guest!</p>
</div>

Component Interaction and Communication

Angular components often need to interact with each other. There are several ways to facilitate this communication:

Input Properties

Input properties allow a parent component to pass data to a child component using property binding.

Example:

In the child component:

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

@Component({
selector: 'app-user-detail',
template: `<p>User: {{ userName }}</p>`
})
export class UserDetailComponent {
@Input() userName!: string;
}

In the parent template:

<app-user-detail [userName]="'John Doe'"></app-user-detail>

Output Properties and Event Emitters

Output properties enable a child component to send data or events back to a parent component.

Example:

In the child component:

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
@Output() message = new EventEmitter<string>();


sendMessage() {
this.message.emit('Hello from Child');
}
}

In the parent template:

<app-child (message)="handleMessage($event)"></app-child>

In the parent component:

handleMessage(event: string) {
console.log(event);
}

Next Article
Article Tags :

Similar Reads