2017-09-04 79 views
1

我想要觸發離子項目滑動元素,當一個特定的類被添加到它。在我的情況下,「主動 - 幻燈片」。我想引用與ViewChild的元素,但我總是得到錯誤ViewChild not working propper(Ionic Element)

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

回答

4

默認@ViewChild()當元件承載部件或指令返回組件實例而不是ElementRef

你需要明確指出你想要的ElementRef

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

參見angular 2/typescript : get hold of an element in the template

+1

感謝。工作像一個恥辱。 –