最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get a reference to the current element in Angular 2? - Stack Overflow

programmeradmin4浏览0评论

For example, I have a function itemDragged(). How, inside that function, to get a reference of ion-item-sliding to get its current class attribute?

<ion-item-sliding *ngFor="let activity of activities" (click)="showModalInfo(activity)" (ionDrag)="itemDragged($event)">

For example, I have a function itemDragged(). How, inside that function, to get a reference of ion-item-sliding to get its current class attribute?

<ion-item-sliding *ngFor="let activity of activities" (click)="showModalInfo(activity)" (ionDrag)="itemDragged($event)">
Share Improve this question edited Nov 15, 2024 at 14:23 Roman C 1 asked Feb 13, 2017 at 12:31 KinKin 4,59614 gold badges59 silver badges114 bronze badges 4
  • Have you checked $event.target? – Satpal Commented Feb 13, 2017 at 12:32
  • @Satpal undefined – Kin Commented Feb 13, 2017 at 12:33
  • i think this might help : stackoverflow./questions/32693061/… – Samy Commented Feb 13, 2017 at 12:43
  • Maybe putting #someVar and passing It to your function (ionDrag)="itemDragged($event, someVar)"? – developer033 Commented Feb 13, 2017 at 12:45
Add a ment  | 

3 Answers 3

Reset to default 5

You can use reference variable in template

<ion-item-sliding #iis *ngFor="let activity of activities" (click)="showModalInfo(activity)" (ionDrag)="itemDragged(iis)">
<p>{{iis.class}}</p>

Would you use a ViewChild, and get the nativeElement?

In the ponent API, note that the key is how you will access it in your code, the value passed to ViewChild is the "#" id you gave the ponent (this is ES6, in TS you'd use the ViewChild annotation):

...
queries { 'myElement' : new ViewChild ( 'myelement' ) }
...

In the markup:

<div #myelement></div>

In your ponent function (a handler, wherever you need to grab it), the nativeElement property gives you a reference to the HTML element, so you can set innerHTML, add a handler, or whatever else you need to do. There's of course other ways to do this by binding to properties (e.g. you can bind to (click) or [innerHTML]):

...
this.myElement.nativeElement... // etc.
...

Alternatively, if you wanted to use a single handler for multiple elements (say, a bunch of different clickable divs) you could use event.target to do the same thing. The problem with that is, because giving IDs is considered "bad" these days, you have to have an alternative way of IDing which DIV got clicked. You can check the label (innerHTML), you can give it a dummy style and check for that, etc.

But digging in the event class you can get the class like this

  itemDragged(event){
    console.log(event._elementRef.nativeElement.className);
  }
发布评论

评论列表(0)

  1. 暂无评论