Working with Angular 4, I am exploring ways to dynamically set a background in my component. The background can either be an Image file or an HTML file.
I have successfully implemented it with the image but facing difficulties with the HTML part.
Any help would be greatly appreciated. Here's what I am trying to achieve: Firstly, I need to check if the file is HTML by using:
if(background.split('.').pop().toLowerCase() === 'html')
If true, then I want to set isHtml to true and use http.get() to fetch the content of the HTML file and assign it to [innerHTML].
Even though it sounds simple, I am having trouble getting it right. Thank you for your assistance.
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>
Update: I have made some progress towards my goal, the only thing left is to read the HTML file with httpService.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;
});
}
});