Setting up an inline style @Input in Angular 2: A step-by-step guide

I am currently working on a component that needs to display random values, which will be generated randomly and passed through some @Input bindings in the template. Everything seems to be going well, but I am facing an issue when trying to link an @Input to a style image URL like this:

<a routerLink="{{nextLink}}" routerLinkActive="active" class="nav-link next" style="background: url('assets/images/{{nextBg}}');">

Here, {{nextBg}} represents a file with its extension e.g. next.jpg => this is my desired outcome.

I have attempted using [ngStyle] and [style.background-image] without success.

Below is my code snippet:

import { Component, Input } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'prev-next',
    template: `
    <nav class="prev-next-nav">
        <a routerLink="{{prevLink}}" routerLinkActive="active" class="nav-link prev" style="background: url('assets/images/tesla.jpg');">
            <span class="link-dir">Previous project</span>
            <span class="link-title"><i class="icon icon-arrowright"></i>&nbsp;{{prevName}}</span>
        </a>
        <a routerLink="{{nextLink}}" routerLinkActive="active" class="nav-link next" style="background: url('assets/images/food.jpg');">
            <span class="link-dir">Next project</span>
            <span class="link-title">{{nextName}}&nbsp;<i class="icon icon-arrowright"></i></span>
        </a>
    </nav>
`
})

export class PrevNextComponent {
    // Previous link inputs
    @Input() prevBg: string;
    @Input() prevName: string;
    @Input() prevLink: string;

    // Next link inputs
    @Input() nextBg: string;
    @Input() nextName: string;
    @Input() nextLink: string;
}

Answer №1

Consider implementing the following approach with the use of [ngStyle]:

<a routerLink="{{prevLink}}" routerLinkActive="active" class="nav-link prev" [ngStyle]="{'background-image': 'url(assets/images/' + prevBg + ')'}">
    <span class="link-dir">Previous project</span>
    <span class="link-title"><i class="icon icon-arrowright"></i>&nbsp;{{prevName}}</span>
</a>

Alternatively, you could utilize the OnInit lifecycle hook to dynamically construct the URLs within the component that make reference to the @Input() prevBg: string;.

HTML

<a routerLink="{{prevLink}}" routerLinkActive="active" class="nav-link prev" [ngStyle]="{'background-image': prevBgUrl}">
    <span class="link-dir">Previous project</span>
    <span class="link-title"><i class="icon icon-arrowright"></i>&nbsp;{{prevName}}</span>
</a>

TS

ngOnInit() {
    this.nextBgUrl = `url(assets/images/${this.nextBg})`;
}

A demonstration has been set up on Plunker. Upon selecting a hero, you will observe the placehold.it image being loaded in the div.foo. The intention is to load the local asset URL in a similar manner.

I trust this information proves beneficial!

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

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Is the runTest.ts class in the vscode-test setup ever utilized in the project? Its purpose remains unclear even in the example project

Being a novice to Typescript, JavaScript, and VScode Extensions I have set up a vscode-test following the guidelines provided here: https://code.visualstudio.com/api/working-with-extensions/testing-extension#custom-setup-with-vscodetest Based on the hel ...

Tips for incorporating WinBox JS into Angular applications

I've been experimenting with the WinBoxJS JavaScript library, and I'm familiar with using it in plain JS. However, I'm now attempting to integrate it into my Angular project. Can anyone guide me on how to achieve this? https://www.npmjs.com/ ...

In the world of Typescript, object-based type inference reigns

I'm grappling with TypeScript to correctly deduce typing in the given code snippet: type Customer = { name: string } type Item = { price: number } const customerConfig = { action: () => [{name: 'Alice'}] as Customer[], } const item ...

The component 'Form' cannot be utilized in JSX because its return type, 'ReactNode', is not a valid JSX element

I'm facing an issue with my Next.js application written in TypeScript after updating react-bootstrap. After the update, I am encountering the following error when attempting to use the Form component from react-bootstrap: react-bootstrap: ^2.10.3 @typ ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...

React: Updating a property in an array of objects causes properties to become undefined

My intention was simply to update a property within an object inside an array and then update the state of the array. However, I encountered an issue where all properties except the one that was updated became undefined. The code in question is as follows ...

The Angular/Express application is in search of outdated JavaScript files within the Chrome browser

When updating and deploying my Angular web app on Google App Engine with an Express server, I encounter a peculiar issue. Upon refreshing the browser, I sometimes face a blank page accompanied by the following error: main.f2b54282bab6f51a.js:1 Failed to lo ...

The clash between the definitions of identifiers in this file and another (@types/jasmine) is causing error TS6200

While trying to build my project with Angular CLI, I am encountering the following error message: ERROR in ../my-app/node_modules/@types/jasmine/index.d.ts(18,1): error TS6200: Definitions of the following identifiers conflict with those in another file: ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

Excessive wait times during the construction of a moderately sized application (over 2 minutes) using TypeScript and loaders like Vue-Loader and TS-Loader

I'm currently utilizing Nuxt 2 with TypeScript and the most up-to-date dependency versions available. Even though my app is of medium size, the compilation time seems excessively slow. Here are my PC specs: Ryzen 7 2700X (8 Cores/16 Threads) 16 GB D ...

How to update an Array<Object> State in ReactJS without causing mutation

In my program, I store an array of objects containing meta information. This is the format for each object. this.state.slotData [{ availability: boolean, id: number, car: { RegistrationNumber : string, ...

Determine in Typescript if a value is a string or not

In my code, I have a component: export type InputData = string | number | null; interface InputData { data?: string | number | null; validate: boolean; } const App: React.FC<InputData> = ({ data = '', validate = true, }) => ...

Troubleshooting the Hide/Show feature in React Native

As a newcomer to React Native development, I am attempting something simple. Within a React Class extending Component, I have 4 components <TouchableOpacity>. In the render function, my goal is to hide three of these components while pressing on one ...

Choose the currently active md-tab within the md-dialog's md-tab-group

I need to create a dynamic md-dialog with an md-tab-group that has two tabs. The md-dialog should open based on the button clicked, displaying the corresponding tab content. The initial template where the md-dialog is triggered: <button md-button class ...

Tips on maintaining a constant number of elements displayed within a container while scrolling using *ngFor

In an effort to improve the performance of loading a large amount of data inside a container div, I implemented a solution. It initially worked fine, but as I continued to append elements to the list while scrolling down, it started to slow down significan ...

When attempting to send an archiver file in NodeJS, the request may become unresponsive

In my NextJS application, I am facing the challenge of generating a large number of QR codes at once, like 300, 400, or even 500, and then packaging them into a zip file for users to download. The following code snippet demonstrates how I achieve this usin ...

Utilize a specific component to enclose particular words within a contenteditable div in an Angular project

I have a task at hand where I need to manipulate text input from a contenteditable division, use regex to identify specific words, and then wrap those words within an angular component. Although I have managed to successfully replace the text with the com ...

Concealing Bootstrap Dialog in Angular 6 through Component隐藏Angular 6中

I have been struggling to hide a bootstrap dialog from a component with no success. Here is my Dialog code: <div class="modal fade" id="loading_video_upload" tabindex="-1" role="dialog" aria-labelledby="loading_video_upload_label" aria-hidde ...

The angulartics2 event is not functioning correctly

I have implemented the angulartics2 library in my project. import { Component } from '@angular/core'; import { Angulartics2On } from 'angulartics2'; @Component({ selector: 'random-component', directives: [Angulartics2On] ...