Saturday 2 July 2016

ng-click in angular 2

ng-click in angular 2 is different from angular js 1. Let us check how it is in angular js 1 first.

Html


<div ng-click="alertValue()">Alert Value</div>

JS


$scope.alertValue = function()
{
   alert('clicked');
}

In angular 2 it is different, see the below example for more info.

Html

Angular is making use of powerful html and css properties. Here (click) syntax is already supported by html, angular 2 is making use of that features.


<div *ngIf="selected">
  <h4>Selected</h4>
  <p>
    <strong>{{selected.name}}</strong>
  </p>
</div>

<h2>{{title}}</h2>
<div>
  <ul>
    <li *ngFor="let i of items">
      <p (click)="showSelected(i)">{{i.name}}</p>
      <p>{{i.exp}}</p>
    </li>
  </ul>
</div>

Here you can notice the syntax different.


//Angular js 1
<div ng-click="alertValue()">Alert Value</div>

//angular js 2
<p (click)="showSelected(i)">{{i.name}}</p>


JS

Let us check the ts file. Here I have used angular 2 + typescript. On click I am showing the selected values.


import {Component} from 'angular2/core'

@Component({
    selector: 'sample-list',
    templateUrl: 'app/sample-list.html',
})
export class sampleComponent {
    title: string;
    items: any[];
    selected:string;
    constructor() {
        this.title = "Angular 2 click";
        this.items = [{
            name:'Prashobh',
            exp:'9',
        },
        {
            name:'Abraham',
            exp:'15',
        },
        {
            name:'George',
            exp:'2',
        },
        {
            name:'John',
            exp:'20',
        }
        ]
    }
    showSelected(item){
        this.selected = item;
    }
}


Click on the name you can see it is appearing in the top of header. Here I have added *ngIf="selected" (ng-if in angular 2)without this it will throw error as the value is not ready.

It will be nice if we add a simple search functionality for this name list. For that please refer this post Angular 2(+) search using pipe.

In this article we have discussed about adding a click event in Angular 2(+).

Related Post

1. How to start with Angular js 2

2. ng-repeat in angular js 2

3. Angular 2 filter using pipe concept

No comments :

Post a Comment