2

I wanna trigger the ion-item-sliding element, when a specific class is added to it. In my case the “active-slide”. I tried to reference to the element with ViewChild but I get always the error

TypeError: Cannot read property 'classList' of undefined

When the clickHandler method gets called.

<ion-list>
  <ion-item-sliding #slideItem>
    <ion-item>
      Item
    </ion-item>
    <ion-item-options side="left">
      <button ion-button (click)="favorite(item)">Favorite</button>
      <button ion-button color="danger" (click)="share(item)">Share</button>
    </ion-item-options>

    <ion-item-options side="right">
      <button ion-button (click)="unread(item)">Unread</button>
    </ion-item-options>
  </ion-item-sliding>
</ion-list>

HTML

export class TestPage { 

  @ViewChild('slideItem') slideItem : ElementRef;

  constructor() {}

  // ...

  @HostListener('click', ['$event'])
  clickHandler(event) {
    console.log("Test 1"); // gets called  

    if(this.slideItem.nativeElement.classList.contains('active-slide'))  {
      console.log("Test 2");  
    }
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
FanaticTyp
  • 195
  • 4
  • 15

1 Answers1

7

By default @ViewChild() returns the component instance instead of the ElementRef when the element hosts a component or directive.

You need to explicitly state that you want the ElementRef

@ViewChild('slideItem', {read: ElementRef}) slideItem : ElementRef;

See also angular 2 / typescript : get hold of an element in the template

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567