Tuesday, January 24, 2017

Looping in Angular 2 using *ngFor directive

The NgFor directive instantiates a template once per item from an iterable.

In Es 2015 we have  "for..of " : loops through the properties of the array
and "for..in"  :loops through the index of the array.



let keyword creates a template input variable



Component
//import angular core
import { Component } from '@angular/core';
//Decorator
@Component({
  selector: 'user',
  template: `
  <ul> 
        <li *ngFor="let hobby of hobbies">
        {{hobby}}
        </li>
  </ul>
      `,
})
//Angular Component
export class UserComponent  { 
 
  hobbies:string [];  
//Constructor
    constructor(){
  
    this.hobbies=['Music','Movies','Sports' ]
  }
}
//interface address{
Index html
<!DOCTYPE html>
<html>
  <head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>

    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading AppComponent content here ...</my-app>
  </body>
</html>

No comments:

Post a Comment