Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript.

In my TypeScript file:

styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",];
    constructor(){
     for (var i = 0; this.styleArray && i <= this.styleArray.length - 1; i++) {
    if (this.arrayTest[0].style == this.styleArray[i]) {

      this.styles = [
        {
          src: './assets/img/' + this.arrayTest[0].style + '.png',
          /* button: this.styleArray[i] + 'InstructionPage', */
          button: 2
        }
      ];
      console.log("First: " + this.styleArray[i]);
    }
  }


   for(var i=0;  this.styleArray && i <= this.styleArray.length -1 ; i++){
   if (this.arrayTest[1].style == this.styleArray[i]){
     this.styles = [
       { src: './assets/img/'+ this.styleArray[i] + '.png',
         button:3
       }
     ];
     console.log("Second: " +this.styleArray[i]);

   }
  }

  // Repeat similar logic for other array items

    }

In my HTML template:

<ion-row>
    <ion-col width-25>
      <ion-card class="card-5 full">
        <img class="list" [src]="styles[0].src" (click)="commonMethod(styles[0].button)" />
      </ion-card>
    </ion-col>
  </ion-row>

  // Repeat similar structure for displaying other image elements

For example: The displayed images should be sorted from highest priority to lowest on the HTML view.

If you encounter an error stating that "src" or "button" is undefined, there might be an issue with how the styles and buttons are being assigned in the TypeScript logic implementation. Check the variable assignments and condition checks to ensure they are correctly assigning values to src and button properties.

Answer №1

There are a few key points that need to be addressed:

  1. Remove the comma at the end of styleArray.

  2. Declare styles outside of the Constructor.

  3. Utilize the Angular image [src] property for displaying images.

Code

 styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal"];
    styles = [{ src: './assets/img/defaultAvatar.png',
                  button: 'someMethod1'},
              ];
    constructor(){
        for(var i=0; this.styleArray && i <= this.styleArray.length -1 ; i++){
            if (this.arrayTest[0].style == this.styleArray[i]){
              this.styles = [
                { src: './assets/img/'+ this.styleArray[i] + '.png',
                  button: 'AuditoryInstructionPage'},
              ];
             console.log("First: " + this.styleArray[i]);
            }
       }
    }
commonMethod(methodName){
    // If function name comes with () then remove by string manipulation
    //This code will call your method by string 
    this[methodName](); // Pass params if required
}

HTML

<ion-row *ngFor = "styleElement in styles">
   <ion-col width-25 >
            <ion-card *ngIf = "styleElement && styleElement.src && styleElement.button" class="card-5 full">
      <img class="list" [src]="styleElement.src" (click)="commonMethod(styleElement.button)" />
    </ion-card>
  </ion-col>
</ion-row>

Answer №2

Since you have the styles stored as an array

this.styles = [
            { src: './assets/img/'+ this.styleArray[i] + '.png',
              button: this.styleArray[i] + 'InstructionPage()'},
          ];

When accessing its properties, make sure to use them like this,

<img class="list" src="{{this.styles[0].src}}" (click)="{{this.styles[0].button}}" />

Update 1 :

//Declare variable
styles:any[] = [];

To prevent errors, utilize ngIf

<ion-row *ngIf="styles.length > 0">
       <ion-col width-25 >
                <ion-card class="card-5 full">
          <img class="list" src="{{this.styles[0].src}}" (click)="{{this.styles.button}}" />
        </ion-card>
      </ion-col>
</ion-row>

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

What is the best way to present retrieved JSON data from a database in Node.js without using the JSON format?

Here is the code snippet: var http=require("http"); var fs = require("fs"); var express = require("express"); var app = express(); var path = require("path"); var mysql = require('mysql'); var ejs = require("ejs") var bodyParser = require(&apos ...

Troubleshooting problems with AngularJS loading data through ajax

One of the custom widgets in my application relies on Angular functionality. On a particular page, this widget is loaded via ajax. The following content is fetched through ajax and inserted into the DOM: _abc.html: <script type="text/javascript">c ...

What is the method for adding an event listener in AngularJS within an ng-repeat iteration?

I'm completely new to AngularJS and currently working on building a photo gallery. The basic idea is to have an initial page displaying thumbnail photos from Twitter and Instagram using an AngularJS ng-repeat loop. When a user hovers over an image, I ...

Encountering a fragment error while utilizing create-react-library

Recently, I embarked on the journey of publishing a React component to npm that I had created. In my quest for knowledge, I stumbled upon create-react-library, which I decided to use for the first time. As I started testing my component from the test folde ...

When the session times out in Angular 5, the previous user's credentials remain on the page instead of being replaced with the current user's information

When switching from one user to another in Angular 5, I am facing an issue where the previous user's credentials are displayed instead of the current user's until I refresh the page. I have tried using the localstorage.clear() method but it doesn ...

React version 18.2.0 and Next.js version 13 faced an issue with hydration failure due to the initial user interface not matching. This problem

Upon opening the page, I encounter an error when focusing on the input element right away. However, if I wait a few seconds before focusing on the input element, the error does not occur. Unfortunately, I have been unable to resolve this issue. Interesting ...

Tips on resolving 'Incompatible platform for [email protected]: expected {"os":"darwin","arch":"any"} (present: {"os":"win32","arch":"x64"})

When testing binary files, everything seemed to be fine until an npm warning about rolling back a failed action popped up (which is probably harmless): An error occurred: EPERM: operation not permitted, lstat 'C:\Users\orca yoon\Doc ...

Extracting data from a nested JSON array within an AngularJS template

Here is some JSON data: { "tracks": [ { "album": { "released": "2013", "href": "spotify:album:3qGeRY1wt4rrLIt1YuSwHR", "name": "The Marshall Mathers LP2 (Deluxe)", "availability": { ...

Error: Unable to use map function on users .. cannot perform mapping on functions

Initially, the map function in my code was working fine. However, suddenly an error started appearing when I included the users.map line. Surprisingly, if I comment out that line, the code works perfectly again. Even more strangely, if I uncomment it, ev ...

Every time I hit the refresh button, I find myself forcefully logged out

After switching from using localStorage to cookies in my React JS web app, I am experiencing an issue where I get logged out whenever I refresh the page. Even though the cookies are still stored in the browser, the authentication process seems to be failin ...

Learn how to effectively showcase various components by leveraging the new react-router-dom v6.0.0 alongside react-redux

My issue is that when I click on a link to render different components, the URL updates but the UI remains unchanged. No matter which item I click on to render, the same thing happens. I've tried numerous solutions to fix this problem without success. ...

How to deactivate a text box within a form that is dynamically generated using Angular

I have encountered an issue with disabling the textbox inside my dynamic form in AngularJS after clicking a button. My code works perfectly fine for disabling textboxes outside the dynamic form, but when I try to target the ID of the textbox within the dyn ...

"Validation with Express-validator now includes checking the field in cookies instead of the request

My current validator is set up like this: const validationSchema = checkSchema({ 'applicant.name': { exists: true, errorMessage: 'Name field is required', }, }); and at the beginning of this route (the rest is not relevant) ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

Acquire the URL using Angular within a local environment

I am currently working on a basic Angular project where I have a JSON file containing some data. [{ "name": "Little Collins", "area": "Bronx", "city": "New York", "coverImage": "https://images.unsplash.com/photo-1576808597967-93bd9aaa6bae?ixlib=rb-1.2.1&a ...

Parsing HTML to access inner content

Currently, I have integrated an onClick event to an anchor tag. When the user interacts with it, my objective is to retrieve the inner HTML without relying on the id attribute. Below is the code snippet that illustrates my approach. Any assistance in acc ...

Why does Res.send return an empty object when console.log indicates it is not empty?

I am currently facing a challenge while using the Google Sheets API with Express, as I have limited experience with JavaScript. My goal is to pass a JSON object from Express to React, but for some reason, when I send the object, it appears empty on the fro ...

Make sure to select the checkbox using a protractor only if it hasn't been checked already

I am attempting to retrieve a list of checkboxes using CSS and only click on a checkbox if it is not already selected. I have successfully obtained the list, but I am encountering an issue when trying to validate whether or not the element is selected. Ca ...

Unable to change the value of Apexcharts components

Utilizing the Vue.js framework along with the Apexchart library, I have been able to create scatterplots for my data. By making use of Axios, I can successfully transmit my data and monitor it using console.log(). With the help of Apexcharts property updat ...

Having trouble with the Twitter share count URL - seeking out other options

Previously, I utilized the following Javascript function to retrieve the Twitter share count for a URL. Unfortunately, Twitter has discontinued providing the share count. Is there a more effective alternative available? // Twitter Shares Count $.getJSON ...