Wednesday, January 25, 2017

Simple Angular 2 toggle function



Angular's *ngIf directive is not subject to style specificity constraints.  It's always safe to use regardless of your stylesheet.   However, it's worth noting that it's not functionally equivalent.  Rather than toggling the display property, it works by adding and removing template elements from the DOM.



user component
//import angular core
import { Component } from '@angular/core';
//Decorator
@Component({
  selector: 'user',
  template: `
  <button (click)=togglehobbies()>{{ showhobbies ? "Hide Hobbies":"Show hobbies"}}
   </button>
  <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=false;
  }
  //functions
  togglehobbies(){
      if(this.showhobbies==true){
      this.showhobbies=false;}
      else{
      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>

No comments:

Post a Comment