Modify the [src] attribute of an image dynamically

I have a component that contains a list of records.

export class HomeComponent implements OnInit {

    public wonders: WonderModel[] = [];

    constructor(private ms: ModelService){
        ms.wonderService.getWonders();
        this.wonders = ms.wonderService.wonderList;
    }

    ngOnInit(){}
}

The values returned by this.wonders look like the array shown in this https://i.sstatic.net/UNopG.jpg.

I'm attempting to dynamically set the image source based on the id value like this:

<div class="img-content" *ngFor="let wonder of wonders">
    <header class="img-content-header">
        <div style="width: 45px; display: table-cell;"> <img [src]="'assets/images/' + wonder.id + '.jpg'" height="40px" width="40px"> </div>
        <div style="display: table-cell;">
            <div>{{wonder.name}}</div>
        </div>
    </header>
</div>

However, I encountered the following error:

Parser Error: Got interpolation ({{}}) where expression was expected at column 14 in [assets/images/{{wonder.id}}.jpg].

Could someone please suggest a possible solution for this issue?

Answer №1

In order to properly bind, follow this method

<img src='{{ "assets/images/" + wonder.id + ".jpg" }}'

Remember that [] cannot be used with {{ }}.

Answer №2

Here is a way to achieve it:

[src]='"assets/pictures/"+inquiry.identity+".jpg"'

Alternatively

src='assets/pictures/{{inquiry.identity}}.jpg'

Answer №3

Utilizing interpolation and property binding is essential in this particular segment

[src]='assets/images/{{wonder.id}}.jpg'

You have the option to eliminate either the property binding

src='assets/images/{{wonder.id}}.jpg'

or get rid of the interpolation altogether

[src]='assets/images/' + wonder.id + '.jpg'

To delve deeper into this topic, explore Property Binding or Interpolation in Angular

Answer №4

When using interpolation, you won't need to include the square brackets [] that are required when constructing a full path in TypeScript and assigning it. Simply removing the [] will suffice.

<img src='assets/images/{{wonder.id}}.jpg' height="40px" width="40px">

The use of [] is necessary when binding a value that originates from TypeScript, as shown in the example below:

<img [src]='path' height="40px" width="40px">

In your TypeScript code, there is a variable named path:

 const path = 'imagepath.jpg'; 

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

Is it possible to customize error messages in @hapi/joi?

Seeking assistance with custom error message overrides in Joi. Consider the schema outlined below. const joiSchema = Joi.object({ name: Joi.string().required(), email: Joi.string().email().required() }) try{ const schema = joiSchema.validateAsyn ...

Troubleshooting the inclusion of nodemon in package.json

I am interested in implementing nodemon to automatically recompile the project when there are changes made to the code during development. package.json { "name": "insurance-web-site", "version": "0.1.0", " ...

ts:Accessing the state within a Redux store

In my rootReducer, I have a collection of normal reducers and slice reducers. To access the state inside these reducers, I am using the useSelector hook. Here is my store setup : const store = configureStore({reducer : rootReducer}); Main Reducer: const ...

Discovering various kinds of data with a single generic type

I am looking to define a specific type like this: type RenderItems<T> = { [K in keyof T]: { label: string; options: { defaultValue: T[K]['options'][current_index_of_array]; item: (value: T[K][&apo ...

I am unable to retrieve information from the server backend

Unable to retrieve data from the backend using the provided token. Testing in Postman shows everything is working fine, but after adding authorization it's not functioning properly. What could be causing this issue? Here is the code snippet: getOrd ...

Converting a JavaScript function to TypeScript with class-like variables inside: a step-by-step guide

During the process of converting a codebase to TypeScript, I encountered something unfamiliar. In particular, there are two functions with what appear to be class-like variables within them. The following function is one that caught my attention: const wai ...

Error encountered with tsc-generated .d.ts files stating "Namespace 'Jimp' not found"

Currently, I am in the process of developing an NPM package, and within my codebase lies a specific class that looks like this: import { MIME_PNG } from 'jimp'; import { IDimensions } from './spritesheet'; /** * Representing a single ...

Using the -t or --testNamePattern in Jest will execute all tests

Currently, I have set up my testing framework using jest and ts-jest based on the guidelines provided by the ts-jest documentation. When I execute the command yarn test --listTests, I can identify the specific test file I intend to run: processNewUser.ts ...

JavaScript: specify parameters for function inputs

I'm curious about optimizing Javascript/Typescript functions arguments for clean code. To demonstrate, let's consider a basic example. Imagine I have a React component with a view property as props: <Grid view="Horizontal" /> ty ...

Developing a firestore query using typescript on a conditional basis

I've encountered an issue while attempting to create a Firestore query conditionally. It seems like there's a TypeScript error popping up, but I can't seem to figure out what's causing it. Here's the snippet of my code: const fetch ...

Issues with NPM start arise moments after incorporating create react app typescript into the project

I've encountered an error while trying to initiate my create react app with Typescript. Despite following all the necessary steps, including adding the .env file (with SKIP_PREFLIGHT_CHECK=true) and updating/reinstalling NPM, I keep facing this issue. ...

Troubleshooting Missing Exports from Local Modules in React Vite (Transitioning from Create React App)

I have encountered an issue while trying to import exported members from local nodejs packages in my project. Everything was working fine with the standard CRA webpack setup, but after switching to Vite, I started getting the following error: Unca ...

Issue encountered with Azure DevOps during TypeScript (TS) build due to a type mismatch error: 'false' being unable to be assigned to type 'Date'. Conversely, the build functions correctly when run locally, despite the type being defined as 'Date | boolean'

I am facing an issue with my NestJS API while trying to build it using Azure DevOps pipeline. The build fails with the following error: src/auth/auth.controller.ts(49,7): error TS2322: Type 'false' is not assignable to type 'Date'. src/ ...

Heroku: Unable to retrieve resource - server returned a 404 (Not Found) status code

I successfully developed my Angular 6 app on my local machine with everything working perfectly. However, after deploying the project to Heroku and running my app here Testing App, I encountered an error in the console browser. Failed to load resource: ...

Encountered a TypeError in Angular printjs: Object(...) function not recognized

I'm currently working on integrating the printJS library into an Angular project to print an image in PNG format. To begin, I added the following import statement: import { printJS } from "print-js/dist/print.min.js"; Next, I implemented the pri ...

What is the process for adding a highlighted area beneath a curve on a high chart?

I am working on creating a high chart with Angular 4 and I have a specific requirement to highlight certain portions of the Highchart. For example, in the image: In the image above, if a data point value drops below a certain limit (such as 0), it shoul ...

"Troubleshooting Typecscript and Angular: Dealing with mismatched argument

How can I resolve this Angular error: (response: HttpResponse<User>) => { which results in the following error message: Argument of type '(response: HttpResponse<User>) => void' is not assignable to parameter of type '(val ...

Troubleshooting Date Errors in Typescript with VueJS

Encountering a peculiar issue with Typescript while attempting to instantiate a new Date object. <template> <div> Testing Date</div> </template> <script lang="ts"> import Vue from "vue"; export default Vue.extend({ name: ...

Encountered an error with create-react-app and MaterialUI: Invalid hook call issue

I am encountering an issue while trying to set up Create-react-app with Material UI. The error message I receive pertains to Hooks. Could there be something else that I am missing? This is the specific error message being displayed: Error: Invalid hook ...

Do Angular FormControl objects have the capability to accept input values of various types, or are they limited to TypeScript primitive types?

When creating a reactive form in Angular using FormControl objects in a FormGroup, I encountered an issue. While passing primitive arguments as values for an HTML input select control works fine, when passing an object of a self-defined class, the value in ...