In Angular, a component template is an HTML file that defines the view for a component. It is where you define the structure and layout of your component's UI. Understanding how to work with component templates is crucial for building dynamic and interactive Angular applications.

Key Concepts

  1. Template Definition: The template can be defined inline within the component or in a separate HTML file.
  2. Data Binding: Templates use data binding to display data from the component class.
  3. Directives: Angular directives can be used within templates to add behavior to the DOM elements.
  4. Template Syntax: Angular provides a rich syntax for templates, including interpolation, property binding, event binding, and more.

Defining a Template

Inline Template

You can define a template directly within the component using the template property.

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

@Component({
  selector: 'app-inline-template',
  template: `
    <h1>Welcome to {{ title }}</h1>
    <p>This is an inline template example.</p>
  `,
  styles: [`
    h1 {
      color: blue;
    }
  `]
})
export class InlineTemplateComponent {
  title = 'Angular';
}

External Template

Alternatively, you can define the template in a separate HTML file and reference it using the templateUrl property.

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

@Component({
  selector: 'app-external-template',
  templateUrl: './external-template.component.html',
  styleUrls: ['./external-template.component.css']
})
export class ExternalTemplateComponent {
  title = 'Angular';
}

external-template.component.html

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

external-template.component.css

h1 {
  color: green;
}

Data Binding in Templates

Interpolation

Interpolation allows you to embed expressions within double curly braces {{ }}.

<h1>{{ title }}</h1>

Property Binding

Property binding allows you to bind the value of a property to an expression.

<img [src]="imageUrl" alt="Image">

Event Binding

Event binding allows you to listen to events and execute methods in response.

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

Two-Way Data Binding

Two-way data binding combines property and event binding using the ngModel directive.

<input [(ngModel)]="name">
<p>Hello, {{ name }}!</p>

Using Directives in Templates

Built-in Directives

Angular provides several built-in directives to manipulate the DOM.

  • ngIf: Conditionally include an element in the DOM.

    <p *ngIf="isVisible">This paragraph is conditionally visible.</p>
    
  • ngFor: Repeat an element for each item in a list.

    <ul>
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>
    

Custom Directives

You can also create custom directives to encapsulate reusable behavior.

import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.renderer.setStyle(this.el.nativeElement, 'color', 'red');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.renderer.removeStyle(this.el.nativeElement, 'color');
  }
}

Usage in Template

<p appHighlight>Hover over this text to see the highlight effect.</p>

Practical Exercise

Task

Create a component with the following requirements:

  1. Define an external template.
  2. Use interpolation to display a title.
  3. Use property binding to set the src attribute of an image.
  4. Use event binding to handle a button click.
  5. Use ngIf to conditionally display a paragraph.
  6. Use ngFor to display a list of items.

Solution

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular Component Templates';
  imageUrl = 'https://angular.io/assets/images/logos/angular/angular.png';
  isVisible = true;
  items = ['Item 1', 'Item 2', 'Item 3'];

  toggleVisibility() {
    this.isVisible = !this.isVisible;
  }
}

app.component.html

<h1>{{ title }}</h1>
<img [src]="imageUrl" alt="Angular Logo">
<button (click)="toggleVisibility()">Toggle Paragraph</button>
<p *ngIf="isVisible">This paragraph is conditionally visible.</p>
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

app.component.css

h1 {
  color: navy;
}

Summary

In this section, you learned about Angular component templates, including how to define them inline or in external files. You explored various data binding techniques such as interpolation, property binding, event binding, and two-way data binding. Additionally, you learned how to use built-in and custom directives within templates. Finally, you completed a practical exercise to reinforce these concepts.

Next, you will learn about component styles and how to apply them to your Angular components.

© Copyright 2024. All rights reserved