Guide to dynamically updating the href of an SVG Image in Angular HTML

I am currently iterating through a list of employee objects, each containing an image URL that I need to incorporate into an SVG - Image element.

<div *ngFor ="emp of employees">
        <defs>
         <pattern id = "attachedImage" height = "100%" width = "100%" patternContentUnits = "objectBoundingBox">
            <image href="{{emp.ImageUrl}}"  preserveAspectRatio = "none" width = "1" height = "1"/>
        </pattern>
        </defs>
        <circle cx = "50%" cy = "50%" r = "35%" fill = "url(#attachedImage)"/>
    </div>

I prefer not to iterate through all the HTML elements in JavaScript. If necessary, I want to associate the correct image with the appropriate object.

Is there a way to dynamically append the URL to this image? I attempted using {{emp.ImageUrl}}, but it did not work as expected.

Here is a URL to a working example where the URL is hardcoded: https://stackblitz.com/edit/angular-pq6r2w

My goal is to add the URL dynamically.

Any suggestions would be greatly appreciated!

Answer №1

The issue with your coding is that you are using the same id for all pattern images, causing the first image to display in all shapes. To resolve this, utilize the ngFor loop index to create unique ids for each image:

<div *ngFor="let emp of employees; let i = index">
  ...
  <svg class="circle-chart" ...>
    ...
    <g class="circle-chart__info">
      <defs>
        <pattern [id]="'attachedImage_' + i" ... >
          <image [attr.xlink:href]="emp.ImageUrl" ... />
        </pattern>
      </defs>
      <circle [attr.fill]="'url(#attachedImage_' + i + ')'" ... />
    </g>
  </svg>
</div>

You can view the outcome on this stackblitz. Additionally, I adjusted the protocol to https for the second image to ensure its visibility within the view.

Answer №2

Although I can't be completely certain, this method seems to be effective for my situation.

Here is a suggested approach:

[source]=emp.PictureLink

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

Pattern Matching for Excluding Multiple Specific Phrases

I need to restrict what a user can enter into a field based on previous entries that are already in the system. For instance, the user has already entered these values into the database: ["typescript", "C#", "python"] If they type one of these existing ...

Facing issues with Laravel errors preventing the implementation of CSS on my localhost

These are the tailwindcss errors I am encountering: npm WARN @tailwindcss/[email protected] requires a peer of tailwindcss@^1.0 but none is installed. You must install peer dependencies yourself. npm WARN @tailwindcss/[email protected] requi ...

Changing the hover color of an Angular Material MD Button

<div class="non-active" layout layout-align='space-around center'> <md-button ng-click="$ctrl.widget.type = 'chart'; $ctrl.validateForm()" layout='column' ng-class="{selIcon : $ctrl.widget.type == ' ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

Using React Native to trigger a function upon receiving a notification

Can a function in javascript be executed in react native when receiving a remote notification? Will a remote notification trigger react native to run in the background? Alternatively, should this be handled with Swift/Objective-C instead? ...

Expand a list item to full width based on the number of items present

Is there a way to make dynamically added list items in a footer stretch across the width of their container? The footer is created in WordPress and the list items are actually widgets. Here is an example: Fiddle I can't manually set the width for e ...

JavaScript 'await' throws error 'then is not defined'

Just starting out with async programming and I've noticed a common issue in similar threads - the problem of not returning anything. However, in my case, I am facing a different error message 'Cannot read property 'then' of undefined&ap ...

Prevent Scrolling on Body with W3 CSS

While implementing scroll body lock packages like body-scroll-lock, react-scrolllock, or tua-body-scroll-lock alongside the W3 CSS package, I have encountered an issue where the body remains unlocked even when the designated element is active or open (e. ...

Using jQuery to swap out intricate background designs

I'm attempting to use jQuery to change the background-color of an element from: background: transparent linear-gradient(#C0B 45%, #C0B) to: background-color:#000; Unfortunately, my attempt to remove the background property with .removeAttr() has n ...

The 'fs' module does not seem to have an immediate impact; a server restart may be necessary for the changes to take

This NodeJS project involves starting the server with npm start. The project reads files from a folder called "./mydir/" using 'fs.readdirSync'. It then pushes these files into an array and prints them on the console. var fs = require('fs ...

Obtain the object literal string with additional decorative strings surrounding it

In my current Typescript code, I have an object literal structured like this: const MyNamesStrings = { a: { b: "hello", c: "bye" } d: { e: "qwerty" } } However, I am looking for a way to wrap these strings with add ...

In certain Express app files, the use of Sequelize modules may result in a return value of undefined

Objective - To implement a middleware-like callback in userHandler located in util.js for certain express routes in an express app, created using express-generator and sequelize-cli. Expected Outcome - Utilize the user model successfully in routes and use ...

Filter Products with Magento Layered Navigation - Checkbox Options

Is there a method to transform the layered navigation into checkboxes similar to Asos? I have noticed that there are modules available for purchase claiming to offer this functionality. I may consider using one of those, but I wanted to explore any other ...

Activate single elements one at a time

If you want to understand the question better, take a look at my code on jsfiddle. Each Div contains only one link. When you click on the link, it sets the Div to active and shows a hidden Div within it. Clicking the link again toggles the active style an ...

"JQuery event handlers not functioning as expected: .click and .on failing

For some time now, I've been facing this issue and I'm at a loss trying to figure it out. I have attempted various solutions such as using .click(), .on(), .delegate, and even utilizing .find() to locate the specific element causing the problem. ...

What is the best way for Flask to host the React public files?

When working with React, I created a folder called ./public/assets, and placed an image inside it. Running npm start worked perfectly fine for me. However, after running npm run build in React, I ended up with a ./build folder. To solve this issue, I moved ...

Row in Bootstrap 3 fails to display correctly on medium-sized devices

Having trouble with divs of different sizes? I want a row that shows 3-column wide divs on medium & large screens and 6-column wide divs on small devices. <div class="container"> <div class="row"> <div class="service col-sm-6 col-md-3"& ...

A guide to displaying a DIV element upon clicking a button in ReactJs

While developing a form, I encountered the need to render the same div in the "Active Membership" section whenever the "Add More" button is pressed. Since users can have multiple active memberships, each time the button is clicked, the input section shou ...

What's the most effective method for handling routes and receiving parameters in ExpressJS?

I have created a unique Express.js system where each file in the /routes folder serves as a separate route for my application. For example, /routes/get/user.js can be accessed using http://localhost:8080/user (the /get denotes the method). You can view m ...

I am utilizing the ternary operator within the map function to dynamically adjust the column width of a material table

Looking to adjust column widths based on the IDs received from the map function. Check out the code snippet: <TableRow> { tableData.header.map(header => { header.i ...