Angular ngx-translate not displaying image

My Angular application is utilizing ngx-translate to support multiple languages. I am trying to dynamically change an image based on the language selected by the user. However, I am facing difficulty in updating the image when a language is clicked. The application supports two languages: 'en' and 'es'.

The code snippet below is from my 'header.component.html', which contains the menu of the application. There is an 'updateSrc()' function present in the click attribute.

<div class="select-box__current" tabindex="1">

  <div class="select-box__value" (click)="useLanguage('es');updateSrc(second_url);">
      <input class="select-box__input" type="radio" id="0" value="1" />
      <p class="select-box__input-text">es</p>
  </div>

  <div class="select-box__value" (click)="useLanguage('en');updateSrc(first_url);">
     <input class="select-box__input" type="radio" id="1" value="2" checked="checked"/>
     <p class="select-box__input-text">en</p>
  </div>

</div>


Furthermore, there is another component named 'looker.component.html' where the image needs to be altered based on the selected language.


<div class="map">

    <img class="graph" src="{{first_url}}" alt="graph">

</div>

In my 'looker.component.ts' file, I am uncertain about how to implement the updateSrc() function to switch to the other URL once a language is clicked. Any guidance on this would be appreciated.


import { Component, OnInit, PLATFORM_ID, Inject } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';

@Component({
  selector: 'app-looker',
  templateUrl: './looker.component.html',
  styleUrls: ['./looker.component.scss']
})
export class LookerComponent implements OnInit {

  first_url: string = "https://storage.googleapis.com/amarello-web-assets/img/graph_2.svg";
  second_url: string = "https://storage.googleapis.com/amarello-web-assets/img/graph_1.svg";

  constructor(
    private title: Title,
    private meta: Meta,
    @Inject(PLATFORM_ID) private platformId: Object
  ) { }

  ngOnInit(): void {
      this.first_url;
  }

  updateSrc(url) {   


  }


}

Answer №1

To dynamically change the image source in Angular, you can utilize property binding on the [src] attribute by assigning it to the value of the first_url property. Then, upon a change event trigger, update the property accordingly as demonstrated below:

HTML

<div class="map">
    <img class="graph" [src]="first_url" alt="graph"> <!--  updated content -->
</div>

TypeScript

import { Component, OnInit, PLATFORM_ID, Inject } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';

@Component({
  selector: 'app-looker',
  templateUrl: './looker.component.html',
  styleUrls: ['./looker.component.scss']
})
export class LookerComponent implements OnInit {

  first_url: string = "https://storage.googleapis.com/amarello-web-assets/img/graph_2.svg";
  second_url: string = "https://storage.googleapis.com/amarello-web-assets/img/graph_1.svg";

  constructor(
    private title: Title,
    private meta: Meta,
    @Inject(PLATFORM_ID) private platformId: Object
  ) { }

  ngOnInit(): void {
  }

  updateSrc(url) {   
      this.first_url = url; // <- modification made here
  }


}

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

Powering up your React components with MDX, Storybook, and Typescript!

Currently, I am attempting to incorporate MDX markup into the creation of live documentation for my storybook. However, upon running the storybook, an error is occurring: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: C ...

The implementation of pushing inside a foreach loop is not correctly adding elements to

I have encountered an issue with running a foreach loop and adding values to an array in my code. The first foreach loop works as expected, adding values properly to the array. However, the second foreach loop seems to be malfunctioning as none of its valu ...

Is the data fetched by getStaticProps consistently the same each time I revisit the page?

When utilizing routes to access a specific page like page/[id].js, the concern arises whether data will be refetched each time the page is visited. For instance, if you navigate to another page through a link and then return to this original page by pres ...

Is it possible to selectively exclude features such as routes and components from my Angular application during the build process based on the environment configuration file?

I am interested in creating two variations of my Application using the same codebase. One version will have the "registration" feature included, while the other will not. Is there a way to configure Angular so that an environment file dictates what is ex ...

Examining current elements in database using Node.js and MySQL

There appears to be a problem with the code inside con.query(query, function (err, result, fields). The issue is that it is never being called. This part of the code is meant to verify that when a user signs up, the email they enter is not already in use. ...

access older siblings, accordion animation

I need assistance achieving an accordion effect on a DIV when hovering over it. The right side of the accordion is functioning properly, but I am facing issues with the left side. You can view my code on jsFiddle Could someone please provide guidance on ...

What causes the closure variable to be reset after iterating over JSON data using $.each method?

Take a look at this scenario: var elements = []; $.getJSON(data_url, function(result) { $.each(result, function(key, value) { elements.push(parser.read(value.data)); // at this point, "elements" contains items }); }); dataLayer.addElements( ...

Cannot save PDF files to a server using jsPDF

I'm new to this community and still learning javascript & php. I am having trouble saving my PDFs with jsPDF to the local storage on the server (automatically generated). It used to work in the past, but now when I add Canvas (javascript) to my HTML, ...

Receiving encoded characters in the response

URL: I have encountered an issue where I am trying to retrieve the PDF file from the URL above using code. In tools like Postman or Insomnia, I am able to see the output as expected in PDF format. However, when I attempt it with code, I am receiving rando ...

"Commitment made ahead of time without allowing for the outcome to

I'm completely new to working with promises and I'm encountering some unexpected behavior in my code. The issue lies in the TaskRunner.SyncObjects function within Main.js, which should be waiting for the selectedCourses variable to be populated ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...

ReactJS mixes up fetch URLs with another fetch_WRONG_FETCH

I have a fetch function in my Home component: export default function Home() { const { rootUrl } = useContext(UserContext); useEffect(() => { fetch(`${rootUrl}/api/products/featuredProducts`) .then((result) => result.json()) .then ...

Formik React struggling with error management and handling tasks accurately

I am currently using the Formik template to develop a Login Form. onSubmit={( values, { setSubmitting, setErrors /* setValues and other goodies */ } ) => { props.logMeIn(va ...

Evaluate a program to identify prime numbers

I am currently working on a JavaScript program that utilizes recursion to determine whether an input is a prime number or not. Within my code, I've defined the isPrime function. The base cases are set to return false when x==1 and true for x==2, cons ...

A regular expression in JavaScript for matching unpredictable numbers without any specific words preceding them

For instance, I am looking to extract the numbers that do not have 'the', 'abc', or 'he' before them; the89 (no match) thisis90 (match 90) iknow89999 (match 89999) getthe984754 (no match) abc58934(no match ...

identifying HTTP requests originating from an embedded iframe

I have a unique scenario where there is an iframe on my page that calls a URL from a different domain. Occasionally, this URL will tunnel to a different URL than the one I specified. Unfortunately, due to cross-domain restrictions, I am unable to view the ...

Running on Node.js, the Promise is activated, yet there remains an issue with the function

I've encountered a strange issue that I can't seem to diagnose. It's showing a TypeError: My code is returning 'function is undefined', which causes the API call to fail. But oddly enough, when I check the logs and breakpoints, it ...

The data type '{ [key: string]: number; }' cannot be assigned to type 'T'

I’m working with a complex TypeScript type and trying to manage it within a function. Here’s what I have: type T = { a: number } | { b: number } function func(k: 'a' | 'b', v: number) { // error message below const t: T = { ...

Creating cohesive stories in Storybook with multiple components

I need assistance with my storybook setup. I have four different icon components and I want to create a single story for all of them instead of individual stories. In my AllIcons.stories.tsx file, I currently have the following: The issue I am facing is ...