Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Click Event on non-form elements

This is about Angular2

How do I listen to events (like Click) on the non-form elements like <li>?

side-bar.html

<div class="col-sm-3 col-md-2 sidebar">
    {{title}}
    <ul class="nav nav-sidebar">
        <li *ng-for="#collection of collections" (click)="liClicked(this)">
            <a href="#">{{ collection }}</a>
        </li>
    </ul>
</div>

SideBarComponent

function SideBarComponent(){
    this.title = "Collections";
    this.collections = ["Collection-1", "Collection-2", "Collection-3", "Collection-4", "Collection-5"];
    this.liClicked = function(el){
        alert('a');
    }
}
SideBarComponent.annotations = [
    new angular.ComponentAnnotation({
        selector:'side-bar'
    }),
    new angular.ViewAnnotation({
        templateUrl: 'templates/side-bar.html',
        directives:[angular.NgFor]
    })
];

A point to be noted here is that, if I replace <a> tag from side-bar.html with a <button> tag, the click event works fine. But for some reason, it doesn't work when I add (click) handler to <li> element.

like image 965
AdityaParab Avatar asked Aug 18 '15 05:08

AdityaParab


3 Answers

Change your code to:

(click)="liClicked($event)"
like image 84
Nish Avatar answered Oct 18 '22 08:10

Nish


I am not familiar with the es5 syntax for angular2, but the "this" you have in your li tag seems weird. Maybe you can try without the parameter in a first place. (click) should work on any element.

If you want to pass the html element the way to do it is : <li #elem *ng-for="#collection of collections" (click)="liClicked(elem)">

like image 8
Arnaud Boeglin Avatar answered Oct 18 '22 07:10

Arnaud Boeglin


As of angular2 is in beta now so according to updated version of angular there is syntax change like this:

*ng-for changed to *ngFor

export class AppComponent { 
  collections: Array<any>= [];
  selected:string= null; 
  constructor(){
    this.collections = ["Collection-1", "Collection-2", "Collection-3", "Collection-4", "Collection-5"];
  }
  FunCalled(a){
    this.selected= a;
    console.log(a);
  }
}

HTML part is:

<div class="col-sm-3 col-md-2 sidebar">
    {{title}}
    <ul class="nav nav-sidebar">
        <li *ngFor="#collection of collections #i=index" (click)="FunCalled(collection)">
            <a href="#">{{ collection }}</a>
        </li>
    </ul>
</div>

Selected Value is : {{selected}}

and here is the example of working with Angular2 Click Event on non-form elements here is the working example:
Working Example

Update

# is not changed with let in the *ngFor. so the update syntax will be

*ngFor="let collection of collections; let i = index"
like image 8
Pardeep Jain Avatar answered Oct 18 '22 06:10

Pardeep Jain