2017-05-15 30 views
1

我基於一個條件創建了Slides。當條件成立時,Slides組件被初始化。Angular,Ionic2每次初始化時都配置@ViewChild

<ion-slides *ngIf="condition === true"> 
    <ion-slide *ngFor="let question of questions"> 
    // slide content 
    </ion-slide> 
</ion-slides> 

Addionally我通過設置onlyExternal = true禁用刷卡。由於這不是輸入屬性,我必須在父組件的ngAfterViewInit方法中設置值。

import { Component, ViewChild, AfterViewInit } from '@angular/core'; 
import { Slides } from 'ionic-angular'; 

@Component{ 
    ... 
} 
export class QuizPage implements AfterViewInit { 
    @ViewChild(Slides) slides: Slides; 
    ... 
    ngAfterViewInit { 
    this.slides.onlyExternal = true; 
    } 
    ... 
} 

當視圖狀態更改Slides -component被破壞,從而失去了onlyExternal設置。當條件滿足時它會被重新初始化,但ngAfterViewInit僅在父組件初始化時調用一次。這意味着onlyExternal設置未設置。

目前我使用ngAfterViewChecked,但它經常被調用,我想知道是否有更好的方法來解決這個問題。

ngAfterViewChecked() { 
    if(this.slides) { 
    this.slides.onlyExternal = true; 
    } 
} 
+0

如何檢查條件? –

+0

@ GabrielBarreto你是什麼意思,爲什麼它重要? –

回答

0

我終於發現另一個問題的解決方案:angular-2-viewchild-in-ngif

甲設定器必須對@ViewChild使用。那個只會調用一次,當ngIf條件改變時。

export class QuizPage { 
    private slides: Slides; 
    @ViewChild(Slides) set slidesViewChold(slides: Slides) { 
    if(slides) { 
     slides.onlyExternal = true; 
    } 
    this.slides = slides; 
    } 
    ... 
} 
0

User ViewChildren並訂閱更改通知。

下面是一個例子 https://plnkr.co/edit/jZBWR6Y4afqhV9g020k2

@Component({ 
    selector: 'my-app', 
    template: ` 
     <div> 
     <button (click)="toggleHello()">Toggle Hello</button> 
     <h2 #vc *ngIf="show">Hello {{name}}</h2> 
     </div> 
    `, 
    }) 
    export class App { 
    show = true; 
    @ViewChildren('vc') h2: QueryList<ElementRef>; 

    name:string; 
    constructor() { 
     this.name = `Angular! v${VERSION.full}` 
    } 

    toggleHello() { 
     this.show = !this.show; 
    } 

    ngAfterViewInit() { 
     this.setAttr(); 
     this.h2.changes.subscribe(()=> { 
     this.setAttr(); 
     } 
    } 

    setAttr() { 
     if(this.show) { 
      this.h2.toArray()[0].nativeElement.style['color']= 'blue'; 
     } 
    } 
    } 
+0

這通常起作用,但不在'* ngIf'塊內。當if條件未滿足時,if內部的組件被破壞。因此@ViewChildren是'undefined'。當它再次可用時,訂閱不再活動。 –

+0

我不確定我是否理解你。在這個例子中,我使用ngIf和ViewChildren。請給我看你的html結構來幫助。 –

+0

一切都包含在我的問題中。 ' ...'是我用'@ViewChild(幻燈片)幻燈片:幻燈片;'訪問的組件。 當'condition'爲'false'時'@ViewChild(Slides)'爲'undefined'。因此'訂閱'不起作用。 –