Wednesday, January 25, 2017

Conditional statements in angular 2



  • { * } marks the directive as the structural directive
  • BrowserModule exposes ng-if and ng-for directives


In the example shown below div is shown if the property showhobbies is true
Component
@Component({
  selector: 'user',
  template: `
  <div *ngIf="showhobbies">
       <h2>hobbies</h2>
          <ul> 
              <li *ngFor="let hobby of hobbies">
             {{hobby}}
         </ul>
      </div>
  
      `,
})
//Angular Component
export class UserComponent  { 
  hobbies:string []; 
  showhobbies:boolean; 
//Constructor
    constructor(){
   
    this.hobbies=['Music','Movies','Sports' ]
    this.showhobbies=true;
  }
}

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>

Conditional statement for an Image Component

//class
export class ProductListComponent{
      showImage:boolean=false;
     
 //functions
 toggleImage():void{
     this.showImage=!this.showImage;
 }
}
html
<td ><img *ngIf='showImage'   >
                        </td>

No comments:

Post a Comment