Setting background images or HTML dynamically within an Angular 4 component

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

Answer №1

At last, the answer has been revealed:

class BackgroundComponent {
public backgroundUrl$: Observable<string>;
public isHtml$ = new Observable<boolean>();
public htmlContent$ = new Observable<string>();

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

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

    this.isHtml$ = this.backgroundUrl$.map(link => link.endsWith('.html'));

    this.htmlContent$ = this.backgroundUrl$
        .filter(link => link.endsWith('.html'))
        .switchMap(link => {
            return this.http.get(link).map(response => response.text());
        });
}
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for optimizing the performance of an Angular 2 website

I am currently developing a website in Angular 2 and have successfully completed one module which I uploaded to the demo path. However, when I tested it using Google Speed Test, it only received a speed score of 37 on desktop and 32 on mobile. Can anyone ...

An out of memory exception while running the ng build command in Docker results in a fatal

Currently, I am facing the challenge of developing the frontend for a web application within a Node.js Docker container on my Windows PC. Due to the limitations in available base Images, I opted for this specific one from DockerHub as it has a substantial ...

Can AngularJs $q promises work alongside async/await syntax?

I am currently working on a unique Angular and AngularJs hybrid application with TypeScript versions 9.07, 1.5.11, and 3.7.5. Our HTTP requests are all handled by a wrapper service written in plain Javascript, which was originally designed for the "legacy" ...

Organize an array of objects based on their corresponding years

I am currently facing a challenge in grouping an array of objects by their respective years. To provide some context, I have a visually appealing horizontal timeline graph created using D3js. My goal is to group events with overlapping dates by the year t ...

Issue with manipulating element styles using jQuery in Angular2

My method of assigning IDs to elements dynamically using *ngFor looks like this: <div *ngFor="let section of questionsBySubCat" class="col-md-12"> <div class="subcat-container"> <h4 class="sub-cat">{{ section?.subcategory }}& ...

Tips for retrieving information from an object or converting it to a particular data type

I'm struggling to figure out how to convert an undefined object into a defined one in Angular TS. I have a table that allows for content modification using a modal window. The data from the row fills the fields of the modal window, and once changes ar ...

Testing a function that involves multiple HTTP requests through unit testing

I am struggling with writing a unit test for a function that indirectly triggers multiple HTTP requests. The service I am testing has the following structure: /* content.service.ts */ import { Injectable } from "@angular/core" import { ApiService } from ...

Is the scrolling functionality acting strange while using React Three Fiber?

In my React Three Fiber application, I have the following structure: Website Canvas NativeHTMLContent Canvas Website The issue I'm facing is that after scrolling down the entire canvas, the scrollbar resets to the top and starts scrolling from the t ...

Encountering a critical issue with Angular 12: FATAL ERROR - The mark-compacts are not working effectively near the heap limit, leading to an allocation failure due

After upgrading my Angular application from version 8 to 12, I encountered an issue. Previously, when I ran ng serve, the application would start the server without any errors. However, after updating to v12, I started receiving an error when I attempted t ...

The template is displaying the string as "[object Object]"

I've implemented code in my ngOnInit function to fetch the translation for a specific text. The following function is being called: async getEmailTranslation() { const email$ = this.translate.get('SUPPORT_TRANSLATE.EMAIL'); this.emai ...

What is the solution for handling the error 'Mismatch between argument types and parameters' in TypeScript while using React Navigation?

Encountered an issue while trying to utilize Typescript in ReactNavigation and received an error from my IDE (WebStorm). Here is my Navigator: export type RootStackParamList = { AppStack: undefined; AuthStack: undefined; }; const RootStack = crea ...

What is the best way to transform an Observable<Observable<HttpEvent<any>>> into an Observable<HttpEvent<any>> within the Angular AuthInterceptor service?

export class AuthInterceptor implements HttpInterceptor { constructor(private usersService: UsersService){} intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return this.usersService ...

Executing services in Angular 2 using class structures

I'm a beginner with Angular 2 and I'm currently working on developing an e-commerce platform. In my project, I have created some fundamental classes for users, items, bids, etc... The User class that I've designed includes several parameters ...

Issue with the onChangeText function in react-native TextInput

import React, {useRef, useState} from 'react'; import {KeyboardAvoidingView, Platform, ScrollView, TextInput} from 'react-native'; import {SafeAreaView} from "react-native-safe-area-context"; export const ProfileScreen: React ...

The parameter of type '{ userInfo: string | null; }' cannot be assigned to type 'never' in this argument

Currently, I am working on creating a context API in React using TypeScript to store user details and tokens. Since I am relatively new to TypeScript, I am facing some challenges understanding the errors below. Can someone please assist me with this? ..... ...

connecting a BehaviorSubject to the [disabled] property of a button

My component has a variable refreshButtonEnabled$ = new BehaviorSubject<boolean>(true); and also a button <button [disabled]="!refreshButtonEnabled$ | async">refresh</button> However, I encountered the following error message: ...

Transforming encoded information into a text format and then reversing the process

I am facing an issue with storing encrypted data in a string format. I have tried using the TextEncoder method but it seems to be creating strings with different bytes compared to the original ArrayBuffer. Here is the line causing the problem: const str ...

What are the best ways to troubleshoot my Angular 2 project?

I've been searching for my TypeScript files in the console, but they're not showing up. I've tried everything to debug my Angular 2 project, but no luck. I can't move forward without debugging, can anyone lend a hand? ...

Error: Overlay provider not found! Check the console for details (Angular Material)

Encountering an error with Angular Material. Specifically, ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[CdkConnectedOverlay -> Overlay]: StaticInjectorError(Platform: core)[CdkConnectedOverlay -> Overlay]: NullInje ...

Error in Angular2 version 2.4.6: Data binding issue with [style.height] set to "300" not working properly

I appreciate your assistance greatly. After downloading Angular-CLI, I created a project using angular2 Version 2.4.6 My project is functioning properly except for one issue - I am unable to use Style Binding directly in HTML anymore. Interestingly, my c ...