Angular Templates: The Key to Building Dynamic and Responsive User Interfaces
Tags: angular, typescript, javascript, css
Published: 2023-01-15 05:29:07

As web developers, we all have come across situations where we have felt how tedious and repetitive it can be to build user interfaces using vanilla HTML. The monotony of writing the same code over and over again, just with slight variations, can make the process of building a website or application very boring. But with Angular templates, that's a thing of the past. Angular templates allow you to create dynamic and interactive user interfaces that are much more engaging and efficient to build.

In this blog, we will explore the capabilities of Angular templates and show you how to take your web development skills to the next level.

Here's a quick look at the topics we'll be covering in this blog, feel free to jump directly to the section that interests you if you are already experienced with templates.

## Pre - Requisite

We will be building upon the concepts of templates and I assume that you have some prior experience working with Angular components. Very advanced knowledge is not required, just a basic understanding of Angular folder structure and the functionality of different files.

Additionally, it would be beneficial to have a general understanding of TypeScript, which is the language used to write Angular applications. However, it is not a mandatory requirement as in the content of this blog we won't be diving deep into Typescript-specific concepts.

With this let's get straight into templates.

## Introduction to Templates in Angular

Templates are code files which render the content onto the UI just like HTML. At first, the word templates may sound scary or complex to developers coming new to Angular, however unlike React (where the code to render to UI is JSX) templates in Angular are written in HTML, which makes them familiar and easy to understand for developers who have experience with web development.

Angular templates also include special syntax and features that allow developers to create truly dynamic and interactive interfaces. For example, templates can include expressions, directives, and components, which can be used to bind data, control the flow of logic, and create reusable UI elements. We will see more on this in further sections with some code examples for a better understanding.

Templates in Angular are used in conjunction with the framework's component-based architecture. Below is the basic structure of a component in Angular, this is assuming a component named _shopping-cart_ (imagine it is a component to handle the cart section of an e-commerce project) :

- **Component File -** This file defines the component class and includes the component's logic and behaviour. For example, a method to iterate over an array of lists and multiply them. It is typically named after the component `shopping-cart.component.ts` .

- **Style File -** Includes the CSS for the component. This too is named after the component, `shopping-cart.component.scss`.

- **Template File -** Includes the HTML structure and layout of the component, named after the component, `shopping-cart.component.html` .

- **Spec File -** This file includes the unit tests for the component usually written in the Jasmine testing framework, named after the component, such as `shopping-cart.component.spec.ts`.

## Understanding the Template Syntax

As we discussed earlier templates are written in HTML, however, in addition to being similar to HTML it provides us much more features that allow you to create dynamic and interactive user interfaces. This also helps keep the codebase clean and maintains good readability.

Two of the very often used special syntax in Angular Templates are Expressions and Directives.

Expressions allow you to bind data to the template, allowing the template to update automatically when the component's data changes. Expressions are enclosed in double curly braces, such as `{{expression}}`.

Below is a very simple code snippet which will help you understand expressions in templates.

```typescript
// test.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-test-component',
  template: `./test.component.html`
})
export class TestComponent {
  testExpression = "Hello World";
}
```
**Code Explanation -** This is a component.ts file which has a variable _testExpression_ and a template `test.component.html` associated with it to render the data from the components. The selector is used to define the HTML element that represents the component. This means that whenever this component is used in another template, it will be represented by an HTML element with the tag name `app-test-component`. This helps in the re-usability of the same component at multiple places.

```HTML
<!-- test.component.html -->
<div>
  The value of the component variable is {{ testExpression }}
</div>
```

As evident, we have easily used the variable `testExpression` in our template to render it. Instead of hardcoding any value and writing it multiple times, we can instead toggle the value in the component.ts file and it will reflect automatically in the UI.

Next is a very interesting and useful concept of Directives which we will learn in more detail in the next section.

Apart from Expressions and Directives, there are a lot more features that Angular templates enable like Reactive Forms, and the use of other components templates which we will discuss and learn in another blog.

Now let's dive into Directives.

## Using Built-in Directives in Angular Templates

Before starting with the usage of directives in templates it is important to understand what are directives. Let me explain it in brief.

Directives increase the functionality of the template by using simple built-in libraries. They are used to extend the capabilities of HTML elements in Angular templates and allow you to create dynamic and interactive user interfaces. There are two types of directives in Angular: structural and attribute directives.

Structural directives change the structure of the DOM by adding, removing or manipulating elements. They are denoted by an asterisk (*) before the directive name. Examples of structural directives include `*ngIf`, `*ngFor` and `*ngSwitch`.

Attribute directives change the appearance or behaviour of an element. They are denoted by no asterisk. Examples of attribute directives include ngClass and `ngStyle`.

Next, let's see how directives make using Angular templates more robust and help us create dynamic UI with the least possible code.

```typescript
// fruits.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-fruits-component',
  template: `./fruits.component.html`
})
export class FruitsComponent {
  isVisible = true;
  fruits = ['apple', 'oranges', 'guava'];
}
```

Code Explanation - `fruits.component.ts` file has a template file named `fruits.component.html`. It has two variables `isVisible` which is a boolean variable with the value **True ** and variable `fruits` which is an array with three fruit names.

We can use these variables in Angular directives to dynamically render the values in UI.

```HTML
// fruits.component.html
<div *ngIf="isVisible">
    <h1>List of Items</h1>
      <ul>
        <li *ngFor="let fruit of fruits">{{ fruit }}</li>
      </ul>
</div>
```

In the above example ***ngIf** check the value of `isVisible`, if it's true only then the `<div>` will render, otherwise, it won't. This can be extended to render any div section on the UI by toggling the value of `isVisible` by defining a method in a component file.

Similarly ***ngFor** is another directive, which iterates over the fruits array present in `component.ts`, and renders it dynamically on the UI, in `<li>` tags.

**Fun Fact -** Have you observed all the directives start with _ng_, this is because these directives are developed by the Angular team. We can create our custom directives too and it is a thumb rule that those should not start with ng.

There are a lot more directives made available by Angular. You can read about them on the official Angular Docs. Let me know below in the comments about any cool directives you come across.

Conclusion

In conclusion, templates in Angular are a powerful tool for creating dynamic and interactive user interfaces. With time when you get more experienced with the syntax and features available to you, such as expressions, directives, forms, and components, you can build truly dynamic and engaging applications. Additionally, separating the template code from the component file allows for better organization of the code and easy maintainability.

Comment below with your thoughts, suggestions or any other feedback on the blog.

Lastly, Your support keeps me going, and I give my 100 percent to these blogs! If you've found value, consider fueling the blog with a coffee ☕️ donation at the below link. 

[**Buy me a COFFEE!**](https://www.buymeacoffee.com/ayushdev)

Thank you! 🙏

Thanks for reading!