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.
Change your code to:
(click)="liClicked($event)"
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)">
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
#
is not changed with let
in the *ngFor. so the update syntax will be
*ngFor="let collection of collections; let i = index"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With