Angular 2 - Structural Directives



Description

The structural directives alter the layout of the DOM by adding, replacing and removing its elements. The two familiar examples of structural directive are listed below:

  • NgFor: It is a repeater directive that customizes data display. It can be used to display a list of items.

  • NgIf: It removes or recreates a part of DOM tree depending on an expression evaluation.

Example

The below example describes use of structural directives in the Angular 2:

<html>
  <head>
    <title>Contact Form</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/tools/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.6/angular2.dev.js"></script>
    <script>
      System.config({
        transpiler: 'typescript',
        typescriptOptions: { emitDecoratorMetadata: true },
        packages: {'app': {defaultExtension: 'ts'}},
        map: { 'app': './angular2/src/app' }
      });
      System.import('app/structural_main')
            .then(null, console.error.bind(console));
    </script>

  </head>
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

The above code includes the following configuration options:

  • You can configure the index.html file using typescript version. The SystemJS transpile the TypeScript to JavaScript before running the application by using the transpiler option.

  • If you do not transpile to JavaScript before running the application, you could see the compiler warnings and errors which are hidden in the browser.

  • The TypeScript generates metadata for each and every class of the code when the emitDecoratorMetadata option is set. If you don't specify this option, large amount of unused metadata will be generated which affects the file size and impact on the application runtime.

  • Angular 2 includes the packages form the app folder where files will have the .ts extension.

  • Next it will load the main component file from the app folder. If there is no main component file found, then it will display the error in the console.

  • When Angular calls the bootstrap function in main.ts, it reads the Component metadata, finds the 'app' selector, locates an element tag named app, and loads the application between those tags.

To run the code, you need the following TypeScript(.ts) files which you need to save under the app folder.

structural_main.ts
import {bootstrap} from 'angular2/platform/browser';       //importing bootstrap function
import {AppComponent} from './structural_app.component';   //importing component function
bootstrap(AppComponent);

Now we will create a component in TypeScript(.ts) file which we will create a view for the component.

structural_app.component.ts
import {Component} from 'angular2/core';

@Component({
  selector: 'my-app',
  template: `
    <h2>{{title}}</h2>
    <p class="alert alert-success" *ngIf="names.length > 2">Currently there are more than 2 names!</p>
    <p class="alert alert-danger" *ngIf="names.length <= 2">Currently there are less than 2 names left!</p>
    <ul>
         <li *ngFor="#nam of names"
           (click)="onNameClicked(nam)"
           >{{ nam.name }}</li>
        </ul>
        <input type="text" [(ngModel)]="selectedName.name">
        <button (click)="onDeleteName()">Delete Name</button><br><br>
        <input type="text" #nam>
        <button (click)="onAddName(nam)">Add Name</button>
  `
})
export class AppComponent {
  title = 'Structural Directives';

  public names = [
    { name: "Kamal"},
    { name: "Mitchel"},
    { name: "Yoon"},
    { name: "Johnson"},
    { name: "Jet Li"}
  ];
  public selectedName = {name : ""};

  onNameClicked(nam) {
    this.selectedName = nam;
  }
  onAddName(nam) {
    this.names.push({name: nam.value});
  }
  onDeleteName() {
    this.names.splice(this.names.indexOf(this.selectedName), 1);
      this.selectedName.name = "";
  }
}
  • The @Component is a decorator which uses configuration object to create the component and its view.

  • The selector creates an instance of the component where it finds <my-app> tag in parent HTML.

  • Next is *ngFor directive creates the view exports which we bind to in the template. The * is a shorthand for using Angular 2 template syntax with the template tag.

  • The local variable nam can be referenced in the template and get the index of the array. When you click on the item value, the onNameClicked() event will get activate and Angular 2 will bind the model name from the array with the local variable of template.

  • The methods onAddName() and onDeleteName() are used to add and delete the items from the list.The onNameClicked() method uses local varaible 'nam' as parameter and display the selected item by using the selectedName object.

Output

Let's carry out the following steps to see how above code works:

  • Save above HTML code as index.html file as how we created in environment chapter and use the above app folder which contains .ts files.

  • Open the terminal window and enter the below command:

    npm start
  • After few moments, a browser tab should open and displays the output as shown below.

OR you can run this file in another way:

  • Save above HTML code as structural_directives.html file in your server root folder.

  • Open this HTML file as http://localhost/structural_directives.html and output as below gets displayed.

Advertisements