FanaticTyp
FanaticTyp

Reputation: 185

ViewChild not working propper (Ionic Element)

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");  
    }
  }
}

Upvotes: 2

Views: 3184

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657356

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

Upvotes: 7

Related Questions