ViewChild不工作的propper(离子元素)

时间:2017-09-04 08:22:32

标签: angular ionic-framework ionic3

当想要添加特定的类时,我想触发ion-item-sliding元素。就我而言,“主动幻灯片”。我试图用ViewChild引用该元素,但我总是得到错误

TypeError: Cannot read property 'classList' of undefined

调用clickHandler方法时。

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

1 个答案:

答案 0 :(得分:4)

默认情况下 .state('your state', { url: '/url', resolve: { someName: function(inject here) { //return something, or redirect to a state...etc } }, templateUrl: 'templates/something.html', controller: 'ExampleCtrl' }) 在元素托管组件或指令时返回组件实例而不是@ViewChild()

您需要明确声明您需要ElementRef

ElementRef

另见angular 2 / typescript : get hold of an element in the template