Working with Templates, Directives and Data Binding in Angular

Introduction

In this article, we’ll understand the different ways we can build a template. for our component and show how to create a linked template for our view. Then we’ll build a component associated with that template and use it as a directive. We’ll understand how to set up data binding using interpolation and display the value of our component class properties in the view. We need some basic logic in the template, so we’ll leverage Angular’s built-in directives.

Overview

we create the user interface using templates, directives, and data binding. Web applications are all about the user interface, and Angular makes it easier to build rich and powerful user interfaces. Angular gives us data binding. so, we can display information and respond to user actions. With the help of Angular directives, we add logic to our HTML, such as if statements and for loops. And using Angular components, we build nested user interface fragments, such as an image rotator or rating stars.

Creating a Template and Component

In the previous article, we built an inline template for our app component. We used the template property to define the template in the component’s metadata.

// employee-list.component.ts

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

@Component({
	selector: 'root-emp',
	template: '<div><h1>{{employeeName}}</h1></div>'
})
export class EmployeeListComponent {
	employeeName: string = 'John'
}

But, this is not the only way we can build a template for our components. So, We can use the template property and define an inline template using a simple quoted string with single or double quotes, or we can define an inline template with a multiline string by enclosing the HTML and ES2015 backticks. The backticks allow composing a string over several lines, making the HTML more readable. We used this technique to build our template in the last module. There are some advantages to defining an inline template using one of these two techniques.

// employee-list.component.ts

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

@Component({
	selector: 'root-emp',
	templateUrl: './employee-list.component.html'
})
export class EmployeeListComponent {
	employeeName: string = 'John'
}

The template is directly defined within the component, keeping the view and the code for that view in one file. It is then easy to match up our data bindings with the class properties, such as the page title in this example.

However, there are disadvantages as well. When defining the HTML in a string, most development tools don’t provide IntelliSense, automatic formatting, and syntax checking, especially as we define more HTML in the template. These issues become challenges. In many cases, the better option is to define a linked template with the HTML in its own file. We can then use the templateUrl property in the component metadata to define the URL of our HTML file.

Interpolation

template raises events to pass user actions & values back to class

When Angular, binding coordinates communication between the component’s class and its template. and often involves passing data. We can pass the values from the class to the template for display. the template raises events to pass user actions or user-entered values back to the class.

data binding with template and component

The double curly braces that signify interpolation are recognizable. The employeeName in this example is bound to a property in the component’s class. Interpolation is a one-way binding, from the class property to the template. Interpolation supports much more than simple properties.

here, We can perform operations such as concatenation or simple calculations.

interpolation with template and component

We can even call a class method, such as getName(). We use interpolation to insert the interpolated strings into the text between HTML elements, as shown here.

export class AppComponent {
    getName(): string {
    employeeName: string = 'John'};
}

{{ 'Employee Name' ' + ' getName() }}

Or, we can use interpolation with element property assignments, as in this example. Here we assign the innerText property of the H1 element to a bound value.

<h1 innerText={{employeeName}}></h1>

Adding Logic with *ngIf Built-in Directives

The directive as a custom HTML element or attribute we use to power up and extend to HTML. We can build our own custom directives or use Angular’s built-in directives.

In the previous example, we’ve seen how to build a component and use it as a custom directive, we used to selector: ‘root-emp’ directive to display our employee-list template. The built-in Angular directives are structural directives. A structural directive modifies the structure, or layout, of a view by adding, removing or manipulating elements and their children.
They help us to power up our HTML with if logic and for loops.

*ngIf Directives

The asterisk in front of the directive name. That marks the directive as a structural directive. NgIf is a structural directive that removes or recreates a part of the DOM tree based on an expression. If the expression assigned to the ngIf evaluates to a false value, the element and its children are removed from the DOM. If the expression evaluates to a true value, a copy of the element and its children are reinserted into the DOM.

For example,

<div class='table-responsive'>
	<table class='table' *ngIf='employees && employees.salary > 5000' >
	
    </table>
</div>
asterisk directive as a structural directive

If we only wanted to show the HTML table and if there are some employees on a list of employees. We use ngIf on a table element and set it to employees and employees salaries. If the employees variable has a value and the employees list has a salary greater than 5000, the table appears in the DOM. If not, the table element and all of its children are removed from the DOM.

Adding Logic with *ngFor Built-in Directives

Another structural directive is ngFor. NgFor repeats a part of the DOM tree, once for each item in an iterable list.

So, we define a block of HTML that defines how we want to display a single item and tell Angular to use that block for displaying each item in the list.

We want to display each employee in a row of a table. We define one table row and its child table data elements. That table row element and its children are then repeated for each employee in the list of employees.

For example,

NgFor repeats a part of the DOM tree
<div class='table-responsive'>
	<table class='table' *ngIf='employees && employees.salary > 5000' >
    <tr *ngFor='let employee of products'>
		<td>{{employee.Name}}</td>
		<td>{{employee.Surname}}</td>
		<td>{{employee.Salary}}</td>
	</tr>	
    </table>
</div>

Now, let’s go to the component, and here, we defined an array for our list of products.

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

@Component({
	selector: 'root-emp',
	templateUrl: './employee-list.component.html'
})
export class EmployeeListComponent {
	employees: any[] = [
	{
	  "Name":"John",
	  "Surname":"mitnick",
	  "Salary":6000
	},
	{
	  "Name":"Robin",
	  "Surname":"Rolin",
	  "Salary":6000
	},
	{
	  "Name":"Jack",
	  "Surname":"Walton",
	  "Salary":5000
	}
	]
}

The employee display in a table row with product properties in the appropriate columns. Using an ngFor structural directive, we repeat this table row and its columns for each employee in the list of employees.

Difference between for In and for Of

ES2015 has both a for of loop and a for in loop. The for of loop is similar to a for each style loop. It iterates over an iterable object, such as an array.

For example, we have an array of employee names, if we use for of to iterate over this list such as an array. The for in loop iterates over the properties of an object.

let names = ['john', 'nick', 'robin']

for(let employee of employees)
{
console.log(employee);
}
//output:- john, nick, robin 

When we working with for in an array such as the array indexes are IEnumerable properties. with integer names and are otherwise identical to general object properties. so we see each array index logged to the console. so, the for in as iterating the index. Since the ngFor directive iterates over iterable objects, not their properties. Angular selected to use the of the keyword in the ngFor expression.

For example,

let names = ['john', 'nick', 'robin']

for(let employee in employees)
{
console.log(employee);
}
//output:- 0, 1, 2 

So, we build component and learn how to use that component as a directive and also understand interpolation.

Leave a Reply

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