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

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

Variables within Angular2 services are resetting when the route changes

I have been utilizing a service to monitor the status of my model. I have several components that need to access the variables and properties of this service. The issue arises when the first component initializes, sets the model, but upon trying to access ...

What role does the empty object type {} play in typescript?

In the @types/React package of the DefinitelyTyped library, I came across this definition: interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement | null; propTypes?: WeakValidationMap&l ...

I am unable to locate the type definition file for 'core-js' at the moment

Currently, I am in the process of developing an application using angular2 along with angular-cli. Surprisingly, angular-in-memory-web-api was not included by default. In order to rectify this, I took the initiative to search for it and manually added the ...

Error during Next.js build: Incompatible types - cannot assign type to 'never'

Encountering an error in the console while attempting to build my project: .next/types/app/facebook/page.ts:8:13 Type error: Type 'OmitWithTag<typeof import("D:/projects/abkh24/client/app/facebook/page"), "metadata" | "defa ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

Disable the functionality of the device's back button to prevent it from going back to the

For my project, I utilize popups to display important information to the user. When a popup is displayed, how can I override the functionality of the device's back button so that instead of navigating to the previous route, it will close the popup? ...

Configuring CORS settings in Angular-cli

Upon making a request to my backend url http://docker-users:5500/users?all=true, which returns a list of users, I encountered an issue with Angular-CLI's localhost url: http://localhost:4200. Even after configuring the proxy.config.json file and addin ...

Using formControlName with an Ionic2 checkbox allows for seamless integration of

Currently facing an obstacle with checkboxes in ionic2. Here is how I am using the checkbox: <ion-item> <ion-label>Agree</ion-label> <ion-checkbox color="dark" id="agree" name='agree' class="form-control" formContro ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

How can I simulate event data while testing a function that is triggered when an event is emitted from another component in Angular integration testing?

Within component A, there is a function responsible for updating the view based on data emitted from component B. The aim is to simply call this function and pass the data without integrating with component B as it would be too complicated for this particu ...

The current version of NPM - typescript is 2.2.2, and we are unable to update it to 2.4.1 due to it being a symlink

While attempting to install TypeScript through NPM, I encountered the error below. Can you help me identify the issue? Command: npm install typescript Error: The installation of TypeScript failed because it requires an update from version 2.2.2 to 2.4. ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

The date format being sent by Angular to Java is incorrect, resulting in the inability to create an object in the

In my coupon system, I am experiencing an issue with the date format. The Java coupon bean has a date.sql startDate and endDate, while the Angular coupon model includes startDate:Date and endDate:Date in its constructor. However, when I display the dates o ...

Remove the color options from the Material UI theme

Can certain color types be excluded from the MUI palette in MUI v5? For example, can background and error colors be removed, allowing only colors defined in a custom theme file to be used? I attempted using 'never' but it did not provide a solut ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

Angular 8: Implementing Form Validation with a Boolean Flag

Within my HTML code, I have a function (change)="limitUser($event)". In Typescript, I utilize a for loop to iterate through each element and determine if the value is less than 10. If it exceeds 10, the inValid = true condition is set. All form fields in m ...

Show image using Typescript model in Angular application

In my Angular (v8) project, I have a profile page where I typically display the user's photo using the following method: <img class="profile-user-img" src="./DemoController/GetPhoto?Id={{rec.Id}}" /> However, I am considering an alternative ap ...

Guide on organizing the Object into a precise structure in Angular

I am looking to transform the current API response object into a more structured format. Current Output let temp = [ { "imagePath": "", "imageDescription": [ { "language": "en ...

Is it possible to inject a descendant component's ancestor of the same type using

When working with Angular's dependency injection, it is possible to inject any ancestor component. For example: @Component({ ... }) export class MyComponent { constructor(_parent: AppComponent) {} } However, in my particular scenario, I am tryin ...