Saturday, August 10, 2019

Angular 2 Structural directives

What are structural directives?

Structural directives are used for changes the DOM layout by adding and removing DOM elements. like ngFor. ngFor structural directive adds or removes elements to the DOM depending on how many elements are there in the given array.

Let's see how to use Structural directives in an Angular 2 application.

How to use built-in Structural directives?

There are some most commonly used built-in Structural directives like ngFor, ngIf etc. Let's see how to use ngFor Structural directive.

The ngFor directive is a repeater directive, it adds/removes elements in our DOM depending on how many elements are in the given array. So for using this ngFor directive, we must have an array list first.

In the "Angular 2 Component" tutorial, We had created an EmployeeList component for showing list of employees. See here in the template of the EmployeeList Component.
  1. <h2>Employee List</h2>
  2. <search-bar [PlaceHolderText]="'Search employee...'"
  3. (Search)="OnEmployeeSearch($event)"></search-bar>
  4. <table class="table table-responsive table-bordered table-striped" myVisibility>
  5. <thead>
  6. <tr>
  7. <th>Employee ID</th>
  8. <th>Employee Name</th>
  9. <th>Contact No</th>
  10. <th>Designation</th>
  11. </tr>
  12. </thead>
  13. <tbody>
  14. <tr
  15. [class.special] = "item.EmployeeID == 1"
  16. [style.color] = "item.EmployeeID == 1? 'white':'black'"
  17. *ngFor="let item of EmployeeList;">
  18. <td>{{item.EmployeeID}}</td>
  19. <td>{{item.FirstName}} {{item.LastName}}</td>
  20. <td>{{item.ContactNo}}</td>
  21. <td>{{item.Designation}}</td>
  22. </tr>
  23. </tbody>
  24. </table>
See here in line 15, we have used *ngFor directive. Here * indicates that it's a structural directive. This is the syntax for using ngFor directive.

What it is doing here? It's adding one tr element in our DOM for each item of the array EmployeeList. And whenever we will add or remove any item in the array, a new element will be added or removed from our DOM.

Let's see what happen when we will add a new item in the EmployeeList array.

I will write code for add a new employee in our EemployeeList array inside setTimeout method  So we can see is ngFor directive automatically add a new element in our DOM for the newly added item in the array or not.
  1. import {Component, OnInit} from '@angular/core'
  2. import {EmployeeModel} from '../Models/EmployeeModel'
  3. @Component({
  4. selector:'employee-list',
  5. templateUrl:'employee-list.component.html',
  6. moduleId: module.id
  7. })
  8. export class EmployeeListComponent implements OnInit{
  9. public EmployeeList: Array<EmployeeModel> = [];
  10. public TotalPageNumber:number = 5;
  11. public LoadIntialData(filterText:string):void{
  12. this.EmployeeList = [{
  13. EmployeeID:1,
  14. FirstName: "Sourav",
  15. LastName:"Mondal",
  16. ContactNo: "1234567890",
  17. Designation:"Software Developer"
  18. },
  19. {
  20. EmployeeID:2,
  21. FirstName: "Rik",
  22. LastName:"Decosta",
  23. ContactNo: "1478523690",
  24. Designation:"Software Developer"
  25. },{
  26. EmployeeID:3,
  27. FirstName: "Jhon",
  28. LastName:"Decosta",
  29. ContactNo: "5874213690",
  30. Designation:"Software Developer"
  31. }];
  32.  
  33. if(filterText !=""){
  34. var afterFilterEmpList: Array<EmployeeModel> = [];
  35. this.EmployeeList.forEach(item=>{
  36. if(item.FirstName.toLowerCase().includes(filterText) ||
  37. item.LastName.toLowerCase().includes(filterText))
  38. {
  39. afterFilterEmpList.push(item);
  40. }
  41. })
  42. this.EmployeeList = afterFilterEmpList;
  43. }
  44. }
  45. ngOnInit(){
  46. this.LoadIntialData("");
  47. setTimeout(()=> {
  48. this.EmployeeList.push({
  49. EmployeeID:4,
  50. FirstName: 'Riki',
  51. LastName:'Roy',
  52. ContactNo: '1245789632',
  53. Designation: 'HR'
  54. });
  55. }, 5000);
  56. }
  57. OnEmployeeSearch(searchText):void{
  58. this.LoadIntialData(searchText);
  59. }
  60. }
Now if we run the application, you can see that a new element will be added in the table after 5 seconds.

The ngFor exports some other values also and those are...
index - return the current index of the iteration,
first - return a boolean value for identifying is the current item is the first item or not in the iteration,
last -  return a boolean value for identifying is the current item is the last item or not in the iteration,even - it also returns a boolean value for identifying is the current item is an even index,
and odd - it returns a boolean value for identifying is the current item is odd index.

We can use this values as per our needs. Like We can use the index value for showing serial no here in this table, what we do most of the time when we are showing a list of items on our web page right?

So let's see how we can do it here.
  1. <h2>Employee List</h2>
  2. <search-bar [PlaceHolderText]="'Search employee...'"
  3. (Search)="OnEmployeeSearch($event)"></search-bar>
  4. <table class="table table-responsive table-bordered table-striped" myVisibility>
  5. <thead>
  6. <tr>
  7. <th>Serial No</th>
  8. <th>Employee ID</th>
  9. <th>Employee Name</th>
  10. <th>Contact No</th>
  11. <th>Designation</th>
  12. </tr>
  13. </thead>
  14. <tbody>
  15. <tr
  16. [class.special] = "item.EmployeeID == 1"
  17. [style.color] = "item.EmployeeID == 1? 'white':'black'"
  18. *ngFor="let item of EmployeeList;let i = index;let even=even; let odd=odd;"
  19. [ngClass]="{'even': even, 'odd' : odd}">
  20. <td>{{i + 1}}</td>
  21. <td>{{item.EmployeeID}}</td>
  22. <td>{{item.FirstName}} {{item.LastName}}</td>
  23. <td>{{item.ContactNo}}</td>
  24. <td>{{item.Designation}}</td>
  25. </tr>
  26. </tbody>
  27. </table>
Now if we run the application, we can see the serial no column is there in the table showing serial no. Also if you see inspect element you can see odd/even class added on table row as per odd/even index item.

Create a custom structural directive in Angular 2

Till now we have learned about built-in structural directives and seen how to use. Let's create a custom structural directive now.
See this image, the pagination control. This is what we are going to create our custom structural directive for.

We do paging to prevent our pages from becoming too long and overwhelming. right?
When we do paging, we do have a value to knowing the total number of pages available. So we can generate the pagination control based on the total page number value.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...