Adi*_*rab 10 javascript angular
这是关于Angular2
我如何在非表格元素上听取事件(如Click)<li>
?
边一个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>
Run Code Online (Sandbox Code Playgroud)
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]
})
];
Run Code Online (Sandbox Code Playgroud)
这里要注意的一点是,如果我用<a>
side-bar.html 替换<button>
标签,那么click事件就可以了.但由于某种原因,当我(click)
向<li>
元素添加处理程序时,它不起作用.
我不熟悉angular2的es5语法,但是你的li标签中的"this"看起来很奇怪.也许你可以在没有参数的情况下尝试.(单击)应该适用于任何元素.
如果你想传递html元素的方法是: <li #elem *ng-for="#collection of collections" (click)="liClicked(elem)">
由于angular2现在处于测试阶段,所以根据角度的更新版本,有如下语法更改:
*ng-for更改为*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);
}
}
Run Code Online (Sandbox Code Playgroud)
HTML部分是:
<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}}
Run Code Online (Sandbox Code Playgroud)
以下是在非表单元素上使用Angular2 Click Event的示例,这是一个工作示例:
Working Example
#
let
在*ngFor中没有改变.所以更新语法将是
*ngFor="let collection of collections; let i = index"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56899 次 |
最近记录: |