2017-02-28 127 views
1

我的代碼屬性更新角2 - 延遲加載指令不能讀取的underfined

import { CameraService, CameraDestinationType, CameraPictureSourceType } from 'angular-cordova/plugin/camera' 
import { LazyloadDirective } from 'achromatic/lazyload' 
@Component({ 
    template: ` 
      <div *ngIf="selected"> 
       <div [lazyload] width="100" height="100"></div> 
      </div> 

    `, 
    providers: [createDiscussionService, CameraService] 
}) 
export class CreateDiscussionComponent { 
    @ViewChild(LazyloadDirective) lazyloadDirective: LazyloadDirective; 
    selected: any = false 
    uploadImage(): void { 
     this.cameraService.getPicture({...}) 
     .subscribe(data_url => { 
      if (data_url) {this.selected = true} 
      this.lazyloadDirective.update(data_url) 
     }) 
    } 
} 

它的作用是,當用戶選擇一張照片,它顯示DIV的包裝,然後將照片數據加載到lazyload DIV

問題:用戶點擊後的照片,我得到這個錯誤

Cannot read property 'update' of undefined

有趣的是,如果我刪除<div *ngIf="selected">一切正常。我懷疑病情可能有一些做與不能夠更新

+0

你在哪裏調用'uploadImage()'? ''lazyloadDirective'在'ngAfterViewInit()之前不會提供' –

+0

我打電話時用戶點擊瀏覽照片按鈕 –

+0

更新了一下這個問題了解更多的細節 –

回答

2

的lazyload當selectedfalse這部分

 <div *ngIf="selected"> 
      <div [lazyload] width="100" height="100"></div> 
     </div> 

不會在DOM存在,因此也沒有LazyloadDirective指令實例。

也許你想使用hidden代替

 <div [hidden]="!selected"> 
      <div [lazyload] width="100" height="100"></div> 
     </div> 

@ViewChildren(),這將更新當truefalse之間selected變化。