How can I update the image source using Angular?

<div class="float-right">

  <span class="language dashboard" data-toggle="dropdown">
    <img class="current" src="us-flag.png" />
  </span>

  <div class="dropdown dashboard">
    <a href="javascript:" (click)="setch('en');" class="dropdown-item">
      <img src="us-flag.png" alt="" />english </a
    >
    <a href="javascript:" (click)="setch('it');" class="dropdown-item">
      <img src="it-flag.png" alt="" />italian </a
    >
  </div>

</div>

this is the jQuery implementation:

$('.dropdown-item').on({
    'click': function(){
    //do other thing
        $('.current').attr('src','it-flag.png');
    }
});

Using Angular 6, I am seeking a way to rewrite this logic in an Angular-friendly manner without relying on jQuery, although I am not very familiar with it.

I intend to implement this logic in the following lifecycle hook:

ngOnInit() {

     //assign from default database language setting
     var dbflag = "it";
     //assign $('.current').attr('src','it-flag.png');

  }

  setch(){
    //change flag class="current"
 }

Do you have any suggestions for rewriting this code using TypeScript in an Angular context?

Answer №1

Here's how you can implement this in HTML:

<div class="align-right">

  <span class="language selection" data-toggle="dropdown">
    <img class="current-flag" src={{selectedFlag}} />
  </span>

  <div class="dropdown selection">
    <a href="javascript:" (click)="setLanguage('en');" class="dropdown-item">
      <img src="us-flag.png" alt="" />English </a
    >
    <a href="javascript:" (click)="setLanguage('it');" class="dropdown-item">
      <img src="it-flag.png" alt="" />Italian </a
    >
  </div>

</div>

In the TypeScript file, declare a new variable and assign the image name to it:

 selectedFlag: string;

  setLanguage(language){   
    if (language == 'it') {
      this.selectedFlag = 'it-flag.png';
    } else {
      this.selectedFlag = 'us-flag.png';
    }
  }

Answer №2

To implement angular binding, simply modify the src attribute to [src]

<div class="float-right">

  <div class="dropdown dashboard">      
    <a href="javascript:" (click)="setch('it');" class="dropdown-item">
      <img [src]="displayedImage" alt="">italian </a
    >
  </div>

</div>

In your component.ts file, make sure to create a variable named displayedImage.

this.displayedImage='it-flag.png';

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

Adjusting the amount of rows and columns in a fluid manner with CSS grid (updated)

After conducting my research, it seems that the most effective way to set the final value of a CSS grid is either by directly specifying it or by creating/manipulating the css :root value. A similar query was previously raised here, although the answers p ...

Dealing with 'ECONNREFUSED' error in React using the Fetch API

In my React code, I am interacting with a third party API. The issue arises when the Avaya One-X client is not running on the target PC, resulting in an "Error connection refused" message being logged continuously in the console due to the code running eve ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

Error with Background component in Next.js-TypeScript when trying to change color on mouseover because Window is not defined

Within my Background component, there is a function that includes an SVG which changes color upon mouseover. While this functionality works fine, I encountered an error when hosting the project using Vercel - "ReferenceError: window is not defined." This i ...

I must adjust the size of images based on the size of the viewer's screen

Hello everyone, I could really use some assistance as I am not an expert programmer but just a site admin. My issue is this: I have a website running on PHP and I want to display images to my members while keeping them within specific size limits so they ...

What is the correct way to implement fetch in a React/Redux/TS application?

Currently, I am developing an application using React, Redux, and TypeScript. I have encountered an issue with Promises and TypeScript. Can you assist me in type-defining functions/Promises? An API call returns a list of post IDs like [1, 2, ..., 1000]. I ...

Saving the state of checkboxes in Angular Material

I am trying to figure out a solution for storing checkbox values, specifically whether they have been checked before or not. For example, I have this dialog: After clicking on a checkbox and then clicking Save, the checkboxes reset to being unchecked when ...

Guide on setting up @types from an NPM module containing the "@" symbol in its title

Installing the node package is easy npm install @gamestdio/timer --save But when attempting to add the corresponding types npm install @types/@gamestdio/timer --save An error occurs Invalid package name "@types/": name can only include URL-friendly ch ...

Passing a JSON object as a parameter in a dynamically created element's click event using JavaScript/AngularJS

How to pass a JSON object as a parameter in the click event of a dynamically created element using JavaScript and AngularJS? var _dataObj = "{"sor_SourcingAgentId":1,"sor_Name":"xx"}" var _dynHtml= '<input type="button" ng-click="fnSelectcustom ...

Developing a customizable datepicker with the ability to select specific months or date ranges

I am currently developing a WebApp using flask and constructing templates in HTML/JS for the front end. I am in need of a datepicker that will provide the user with the option to choose a specific date range or select a range of months. Take a look at the ...

Appending or removing a row in the P-Table will result in updates to the JSON

My task involves implementing CRUD (Create, Read, Update, Delete) functionality for my table. While Create, Read, and Update are working fine with the JSON file, I am struggling to figure out how to delete a specific row in the table without using JQuery o ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

Tips for incorporating Vue.js tag attributes in IDEA

I am using IDEA 2016.2.5 and I'm trying to incorporate Vue.js into my project. However, Vue has some tag attributes that IDEA is not recognizing and keeps highlighting as errors. I have installed the Vue Plugin and tried setting the HTML custom unkno ...

Ways to implement a setTimeout function to return to the initial div element?

I have a unique setup on my webpage with three divs. The first div features an html5 video, the second div contains buttons for interaction, and the third div acts as a thank you page that loops back to the beginning like a photo slide. I have shared my co ...

What is the process of declaring internal class variables within class methods in JavaScript?

Here's a query related to React JS. Can I define internal class variables within a method and then use them in other methods? For instance: class Something extends React.Component { state = { value: 'doesnt matter' }; somethin ...

I am facing issues with my submit buttons as they are not functioning

Once I hit the submit buttons, there seems to be an issue with redirecting to another page. Could anyone assist in identifying the error within this code and why my buttons "typ1" and "cod" are not redirecting to the specified location? <?php inc ...

JavaScript's addition function is not functioning properly

Does anyone know how to calculate the sum of these variables? var totalPrice = document.values.T1.value; var pounds = document.values.T2.value; var serviceFee = 5.00 var counter1 = 0; var counter2 = 0; var processing = 0; var shippingCost = 0; var ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...