The SVG updated with data-binding for the href is not showing the new image, despite being successfully updated

I am trying to implement a simple SVG display in my component that switches between image A and B on button click. Below is my current template:

<svg>
    <use [attr.xlink:href]="getIconLink()"></use>
</svg>
<div (click)="changeImageValue()"></div>

Here is the relevant code for interactivity:

currentIcon = "potato"

changeImageValue() {
    if (this.currentIcon == "potato") {
        this.currentIcon = "tomato";
    } else {
        this.currentIcon = "potato";
    }
}

getIconLink(): string {
    if (this.currentIcon == "potato") {
        return "someLinkToAPotato";
    } else {
        return "someLinkToATomato";
    }
}

While inspecting the element in Chrome, I noticed that the href value updates correctly, but the rendered image does not reload. What could be causing the binding to work properly while the SVG rendering remains unchanged? Is there a way to force a refresh?

I have added logs in all methods and confirmed that they are called at the correct times and change the values as expected. It seems like it's just the rendering of the image that is not updating.

Answer №1

Force the DOM update by utilizing changeDetectorRef.

import { ChangeDetectorRef } from '@angular/core';

constructor(private _cd: ChangeDetectorRef) {}

updateIcon() {
    if (this.currIcon == "apple") {
        this.currIcon = "banana";
    } else {
        this.currIcon = "apple";
    }
    this._cd.detectChanges(); // <- trigger DOM update
}

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

Challenges in handling parameters with Angular routing in a Spring Boot application

I'm currently working on developing a UI service using Eureka Client, Ribbon Client, Spring Boot, and Angular. The front end in Angular includes the following routing setup: const routes: Routes = [ { path: 'home', component: HomeComponent ...

Discover the best way to traverse a map in Typescript: Which is the preferred method - for...in, for...of, or

Currently, I am grappling with understanding the syntax required to iterate through a map in Typescript. All the keys in this particular map are strings, while the values associated with them consist of arrays of strings. Below is an excerpt of the sample ...

How to assign a value to a component variable using props in Vue.js

I am attempting to assign a props value to my component variable. Below is the code I'm working with: export default { props: { // eslint-disable-next-line vue/require-default-prop multiPaginatedTableTitle: { type: Stri ...

No issues with TypeScript when referencing an undefined global variable within a function

My journey with typescript has just begun. I had the impression that it was designed to catch mistakes like this, but perhaps my understanding is lacking. The issue arises when attempting something similar to the following: interface A { prop: string } ...

Challenge encountered when setting new values to an object depending on its existing values

I am facing an issue with a data object that stores values and their previous values. The keys for the previous values are suffixed with ":previous" e.g. foo and foo:previous. However, I encountered a type error when trying to assign values to the previous ...

I am unable to simply import lodash.add into my Angular 4 project

I'm struggling to import the add method from the lodash library using Angular 4 and TypeScript. I've attempted various approaches: import { add } from 'lodash'; import { add } from 'lodash/add'; import * as add from 'l ...

Clearing data initialized in a service constructor upon user logout in Angular

In my current setup, I am utilizing a GlobalDataService, which I discovered from this post on Stack Overflow ( source here ), to store response data from a login API in a global variable. This data is then used for subsequent API calls. login(): if (_to ...

Tips for accessing the value stored within the parent element

As someone who is new to the world of javascript and typescript, I am currently working on an ionic application that involves fetching a list of values from a database. These values are then stored in an array, which is used to dynamically create ion-items ...

How does the concept of precedence apply when delivering services across various directives?

In order to customize component behavior by adding directives, I am exploring a method where I define the behavior in service classes that are provided to and from the component. Each directive has its own service provider, allowing it to override the prov ...

Displaying login error messages using Angular form validation

I'm looking to display an error message of 'Invalid username or password' on the login page whenever a user enters incorrect credentials. Below is my auth.service.ts code: signinUser(email: string, password: string) { firebase.auth(). ...

Enabling scrolling for a designated section of the website

Example Link to Plunker <clr-main-container> <div class="content-container"> <div class="content-area"> <div class="row"> <div class="col-xs-9" style="height:100%; border-right: 1px solid rgb(204, 204, 204); padding-ri ...

What steps can be taken to ensure the visibility and accessibility of two vertically stacked/overlapped Html input elements in HTML?

I have encountered a challenge with my HTML input elements. There are two input elements that overlap each other, and I would like to make both inputs visible while only allowing the top input to be editable. I have tried several approaches involving z-ind ...

What is the best way to reproduce the appearance of a div from a web page when printing using typescript in Angular 4?

Whenever I try to print a div from the webpage, the elements of the div end up on the side of the print tab instead. How can I fix this issue? Below is my current print function: print(): void { let printContents, popupWin; printContents = document.getEl ...

What steps do I need to take to create a pristine build of the Microsoft/VSCode source code?

Currently working on setting up a fresh development environment for microsoft/vscode. As a beginner in JS, TS, NPM, and Yarn, which specific command should I run in order to delete all build artifacts and output files and compile the code changes I made? ...

Utilizing Lodash for Effective Grouping of Arrays of Objects

Here is an example of an array of objects: [ { item: "123", categories: [A,B,C] }, { item: "456", categories: [B,C] }, { item: "789", categories: [C,D,E] } ] I'm exploring usi ...

How can I retrieve the /api/auth/me resource serverside using the NextJS AppRouter?

I am looking to implement app router in my Next.js project and have encountered an issue. In order for my app to function properly, I need to make a call to /api/auth/me which will return either a user object or null if the user is not logged in. To achiev ...

What is the best way to elegantly extract a subset array from an array of objects?

Imagine you have the following array of objects: var myObject = [ {A:1, B:2, C:3}, {A:4, B:5, C:6}, {A:7, B:8, C:9}, ] How would you efficiently retrieve a subset with the Y values from this array? var subset = [ B:2, B:5, B:8 ] ...

Error SCRIPT1002 was encountered in the vendor.js file while using Angular 8 on Internet Explorer 11

Having trouble getting Angular to function properly in IE 11. I've tried all the solutions I could find online. The errors I'm encountering are as follows: SCRIPT1002: Syntax error File: vendor.js, Line: 110874, Column: 40 At line 110874 args[ ...

Steps for gracefully throwing an error to an Angular RxJS Observable consumer

How can I handle errors from the 'BROKEN' line in this function so that they are passed to its subscriber, similar to how the 'WORKS' line does? I have observed that the 'Works' line successfully sends the error to this funct ...

What is the method to enable my ngDropdown menu to activate on hover rather than click?

I am currently using an Angular Bootstrap template and I am trying to trigger the dropdown event when hovering over it with my mouse, rather than clicking on it. Can someone please advise me on how to achieve this? <div ngbDropdown class="d-inlin ...