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

Using Puppeteer to Retrieve Data from a Web Page with Multiple Divs of the Same Class

I am in the process of creating a puppeteer script to scrape an announcements website. The challenge I am facing is how to extract the content of each page element with the same class using a loop. Upon inspecting the DOM, it's evident that all the co ...

The responsiveness of Slick Slider's breakpoints is malfunctioning

After implementing a slider using slick slider, I encountered an issue with the width when testing it online and in a normal HTML file. If anyone could assist me in resolving this issue, I would greatly appreciate it. Please inspect the code for both scen ...

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

Creating movement in three distinct divisions

I am seeking a way to have three divs flying in upon click. The first DIV is positioned at the top, followed by one on the left and one on the right (both being below the top one). I wish for them to fly in from their respective directions - the top div fr ...

I am being thrown an npm ERR! by Heroku because it says there is a missing script called "start"

I'm facing issues while trying to deploy a simple app on Heroku. The application keeps crashing and these errors keep popping up. In my setup, I have included: "start": "node app.js", The Procfile also contains the command &a ...

Cease the interval once the array is devoid of elements

I'm currently working on simulating typing effects for incoming server messages by adding an interval to the output. Here's what I have so far: const stream = interval(1000) .pipe( map((): Message => { return messages.pop(); }) ); ...

I encountered an eslint error when I was trying to configure Vue 3 + Quasar with a Firebase config.ts file. The error stated that there was an unsafe assignment of an `

Recently, I set up a new Vue 3 project with Quasar using the Quasar CLI. In order to store my firebase configuration, I created a new file called src/firebase/config.ts, which looks like this: // Import necessary functions from SDKs import { initializeApp ...

Transitioning from embedded browser to system browser in a Next.js / React.JS application

I'm currently dealing with an issue on my Next.js payment page and could really use some expertise. Here's the situation at hand: My payment page has a QR code that directs users to the payment page created with Next.js. When users scan this QR ...

Preventing dragging in Vis.js nodes after a double click: a definitive guide

Working with my Vis.js network, I have set up an event listener to capture double clicks on a node. ISSUE: After double-clicking a node, it unexpectedly starts dragging and remains attached to the mouse cursor until clicked again. How can I prevent this b ...

Exploring the Diversity of Forms with Ajax and JQuery

$(document).ready(function () { $("#addrow").click(function () { var newRow = '<tr><td><input type="text" class="item_code form-control" placeholder="Item Code" name="item_code[]"></td><td><input type="text" ...

Experiencing issues with passwords in nodemailer and node

Currently, I am utilizing nodemailer in conjunction with Gmail and facing a dilemma regarding the inclusion of my password. The predicament stems from the fact that my password contains both single and double quotes, for example: my"annoying'password. ...

Create a new array by dynamically generating a key while comparing two existing arrays

One of the features in my app involves retrieving data from an API and storing it in $scope.newz. The previous user activity is loaded from LocalStorage as bookmarkData. I am facing a challenge with comparing the contentId values in arrays $scope.newz an ...

Discover the Magic of Angular 8 and Bootstrap 4 Tooltips

I'm trying to implement tooltips from Bootstrap 4 into my web application. According to Bootstrap documentation, I should initialize the tooltips with the following code: $(function () { $('[data-toggle="tooltip"]').tooltip() }) (Implement ...

Upon clicking a button, I aim to retrieve the data from the rows that the user has checked. I am currently unsure of how to iterate through the rows in my mat-table

My goal is to iterate through the column of my mat-table to identify the rows that have been checked, and then store the data of those rows in an array. <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()" (c ...

List-style-type outside of a table's boundaries

I recently experimented with using <ol> as list elements within a table in order to dynamically insert new table rows. <table> <thead> <tr> <th>head</th> <th>head</th> <th>h ...

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

Issues with the proper functionality of the .ajax() method in Django

I'm currently facing an issue with my Ajax code while trying to interact with the database in order to edit model instances. I noticed that the first alert statement is functioning correctly, however, the subsequent alert statements are not working as ...

Having trouble simulating JavaScript Math.random in Jest?

Math.random() seems to always return random values instead of the mocked ones. script.test.js jest.spyOn(global.Math, "random").mockReturnValue(0.123456789); const html = fs.readFileSync(path.resolve(__dirname, "./script.html"), " ...

Sorting by date and time in a data grid using MUI X is simple with these steps

In the MaterialUI X data grid, I am facing an issue with sorting a column of dates in the format of DD/MM/YYYY HH:mm:ss. Currently, the default sorting only considers the date and does not account for the time which is causing issues with the order. I was ...

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...