2017-08-08 53 views
0

我正在與角4一起工作。我試圖在我的組件中動態地設置背景。在我的情況下,背景可能是圖像文件或Html文件。動態設置圖像或HTML作爲背景在角4組件

我設法做到了與圖像,但我有問題的Html部分。

我希望我們有所幫助: 首先我要檢查,如果我的文件是HTML像這樣:if(background.split('.').pop().toLowerCase() === 'html')

如果爲true,則設置isHtml爲真,並與http.get的幫助()讀取內容的HTML文件,這就是我想給[innerHtml]。

雖然看起來很簡單,但我無法做到正確。謝謝您的幫助。

HomeBackgroundComponent.ts

export class HomeBackgroundComponent { 
public backgroundPath$: Observable<string>; 
public isHtml = new BehaviorSubject<boolean>(false); 

constructor(public viewContext: ViewContextService, private vlmService: VlmService, private httpService: Http) { 
    viewContext.title = 'Home'; 
    viewContext.id = 'HomeBackgroundComponent'; 

    this.backgroundPath$ = vlmService.background$.map(background => { 
     return '../../../assets/background/' + background; 
    }); 
} 
} 

HomeBackgroundComponent.html

<div> 
    <img *ngIf="!(isHtml | async)" [src]="backgroundPath$ | async" /> 
    <div *ngIf="(isHtml | async)" [innerHTML]="(backgroundPath$ | async)"></div> 
</div> 

更新:我現在有點接近我想要完成的唯一缺少用httpSe讀取html文件的東西rvice.get()

vlmService.background$.subscribe(background => { 
     if (background.split('.').pop().toLowerCase() === 'html') { 
      this.isHtml.next(true); 

      this.backgroundPath$ = vlmService.background$.map(bkg => { 
       // TODO: here should be this.httpService.get(the html file) 
       return '<h1>HELLO DEVID</h1>'; 
      }); 

     } else { 
      this.isHtml.next(false); 

      this.backgroundPath$ = vlmService.background$.map(bkg => { 
       return '../../../assets/background/' + bkg; 
      }); 
     } 
    }); 
+0

問題是什麼? – RRForUI

+0

第一個問題是:用http.get()讀取例如test.html的html文件並將其存儲在backGroundPath $變量中。 – Devid

回答

0

這裏是最後的解決辦法:

export class HomeBackgroundComponent { 
public backgroundPath$: Observable<string>; 
public isHtml$ = new Observable<boolean>(); 
public htmlFile$ = new Observable<string>(); 

constructor(public viewContext: ViewContextService, private vlmService: VlmService, private http: Http) { 
    viewContext.title = 'Home'; 
    viewContext.id = 'HomeBackgroundComponent'; 

    this.backgroundPath$ = vlmService.background$.map(background => { 
     return '../../../assets/customize/' + background; 
    }); 

    this.isHtml$ = this.backgroundPath$.map(path => path.endsWith('.html')); 

    this.htmlFile$ = this.backgroundPath$ 
     .filter(path => path.endsWith('.html')) 
     .switchMap(path => { 
      return this.http.get(path).map(response => response.text()); 
     }); 
} 
}