简体   繁体   English

在 Angular 2 中按类绑定点击事件

[英]Bind click event by class in Angular 2

Let's say I have the following template:假设我有以下模板:

<ul>
 <li id="1" class="selectModal">First</li>
 <li id="2" class="selectModal">Second</li>
 <li id="2" class="selectModal">Third</li>
</ul>

How can I bind a click event by class in TypeScript, so when a li element is clicked I can get the element and query the ID or any other attribute of the clicked element?如何在 TypeScript 中按类绑定单击事件,以便在单击 li 元素时获取该元素并查询被单击元素的 ID 或任何其他属性?

There are many ways to do that.有很多方法可以做到这一点。 Straight forward solution:直接解决方案:

<ul (click)="onClick($event.target)">
 <li id="1" class="selectModal">First</li>
 <li id="2" class="selectModal">Second</li>
 <li id="2" class="selectModal">Third</li>
</ul>

onClick(e:HTMLElement){
    console.log(e.id, e.className);
}

Yes, you can, but it depends on the strategy.是的,你可以,但这取决于策略。 You could do it by JQuery or using the DOM accessors.您可以通过 JQuery 或使用 DOM 访问器来完成。 In my team we use JQuery but we don`t search the entire DOM to find the elements, instead, we use a class called ElementRef:在我的团队中,我们使用 JQuery,但我们不会搜索整个 DOM 来查找元素,而是使用一个名为 ElementRef 的类:

import { ElementRef } from '@angular/core';
...
constructor(private elementRef : ElementRef) {
}

ngAfterViewInit() {
    jQuery(this.elementRef.nativeElement).find('selectModal').on('click', () => {
    //do something here
    });
}

The ElementRef class is a reference for the component itself in the DOM. ElementRef 类是 DOM 中组件本身的引用。 So we're able to filter the search to this component.所以我们能够过滤搜索到这个组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM