Monday, November 21, 2016

Angular 2 Part 2.1 - Structure Directive

A directive (within Angular) is how we add dynamic behavior to HTML.

There are 3 different kinds of directives
  1. Component - Directive with a template.
  2. Structure - Alters layout by adding, removing or replacing DOM HTML elements. Example: ngFor and ngIf.
  3. Attribute - change the appearance or behavior of an element.
Below code is an example how we add a property and array object into Component and display in index.html using selector.
  • ngFor is structure directive. Loops through an array.
  • ngIf is another structure directive. It allows us to evaluate conditionals, show content conditionally.
@Component({
  selector: "my-app",
  template: `
    <h1>{{title}}</h1>
    <ul>
      <!-- carParts in an array object defined in AppComponent Class. -->
      <!-- carPart is a local variable. -->
      <li *ngFor="let carPart of carParts">
        <h2>{{carPart.name}}</h2>
        <p>{{carPart.description}}</p>
        <p *ngIf="carPart.inStock > 0">{{carPart.inStock}} in stock</p>
        <p *ngIf="carPart.inStock === 0">Out of stock</p>
      </li>
    </ul>
  `
})
class AppComponent{   title = "Ultra Racing",  // Example of property   carParts = [{       "id":1,     "name":"Super Tires",     "description":"These tires are the very best",     "inStock":5   },   {   "id":2, "name":"Reinforced shocks", "description":"Shock made from krytonite", "inStock":4 }, {     "id":3,     "name":"Padded Seats",     "description":"Super soft scats for a smooth ride.",     "inStock":0   }] // Example of object }
Enter command "npm start" to run the application.



















Download Car Part Source:
https://github.com/htsiah/angular2-carparts

No comments:

Post a Comment