Angular 2/4/5 Displaying Data in Your Templates

In this tutorial I explain how to display content in you HTML template. Fist we need to open our annular project. For open your project need to open command prompt(CLI) then traverse to your project directory then write  command “code .” then write command “npm start” to run your angular project. After open project in Visual studio code it will display like this screen. Also you can refer my these article to open project in code.

After open project now how to display the content in your angular.

  1. *ngFor Loop:
    For Array(objects) value display in one by one for that “*ngFor” loop available.
    In below screenshot you can see the lists of the users. that’s assign in constructor of the class. Now display these values in our HTML we use “*ngFor” loop like.
    <li *ngFor=”let l of lists”>{{l}}</li>

    Syntax for *ngFor Loop.

    You can see the output in our HTML it display lists of all users one by one. Its simple loop to print object in our HTML. You can specified index of that elements  by following syntax

    <li *ngFor=”let l of lists;let i=index”>{{i}} – {{l}}</li>
    If you doesn’t want to use HTML tags for loop. You need to use angular “<ng-template>” directive for run For loop and its syntax also different.
    Without index it writes like

    <ng-template ngFor let-l [ngForOf]=”lists”>{{l}}</ng-template>

    With index syntax it writes like
    <ng-template ngFor let-l [ngForOf]=”lists” let-i=”index”>{{i}} – {{l}}</ng-template>
    From these ways you can draw your array in your angular template to display data
  2. *ngIf  Loop
    Using *ngIf  loop you can hide & display of any elements in your code. Here is the syntax how to use these with html tags.
    ‘<div *ngIf=”flag”> Text </div>’ : In this condition if flag true then only it will display output otherwise it will not display.

    ‘<div *ngIf=”flag == ‘text'”> Text </div>’ :  You can comparing value with that variable.

    You can write else statement of  if loop. For that you can pass id of the else template. You can write in ng-template with that ID with leading Hash. it will display when condition in else loop.

If anyone have issue you can comment below it. I will give you solution of it.
In next tutorial i will discuss on the “ngSwitch”,”hidden” & how to embed html in your template.

Spread the love
  • 50