Using ngFor and click function in Ionic and Angular

Recently, I delved into the world of Ionic and started working on an app that features a unique 'dictionary' functionality. The app allows users to press a button to hear either an English or German translation of a Dutch word through an audio file. To achieve this, I am utilizing an array within a JSON file named 'Opdracht1.json'. This file contains values mapping translations from Dutch to English/German. Although there are X&Y coordinates for rectangle positions, they are not crucial to the overall functionality. Ultimately, the desired output is to retrieve either an English or German word based on user interaction.

[
    {"x": "365", "y": "12", "string": "steiger", "engels": "Jetty", "duits": "Der Steiger"},
    {...}
]

Upon navigation from a previous page, I determine the required language ('engels' or 'duits').

// Retrieve language from previous page and assign it to 'taal'
this.taal = navParams.get('taal');
console.log(this.taal);

The current approach involves implementing a for loop for clickable rectangles within an SVG element to play corresponding 'audio' files. In the click function, I am attempting to accurately identify the language associated with the clicked item.

<svg viewBox="0 0 1280 720" *ngIf="id === 'SamenwerkenOpDeCorridor'">
  <image width="1280" height="720" xlink:href="assets/imgs/maps/SamenwerkenOpDeCorridor/opdracht1.svg">
  </image>

  <rect *ngFor="let item of coordinaten" [attr.x]="item.x" [attr.y]="item.y" width="200" height="45" fill="#fff" opacity="0" (click)="clickOnArea(item.taal)"
  />

</svg>

Hence, obtaining the correct language in the click function is imperative. While coding it directly as "clickOnArea(item.engels)" proves functional, the aim is to make this process more dynamic.

Answer №1

A simple approach is to utilize the ternary operator.

(click)= "clickButtonByLanguageSelection(taal === 'english'? item.english : item.german)"

Answer №2

To access the key on the object, you can do it like this to ensure future compatibility if more languages are added

clickOnArea(Item){
    let text = Item[this.taal];

    if(!text){
       text = ""; //set default
    }
    //use the value...
}

All you need to do is pass item to the function in the HTML.

Answer №3

In my opinion, this method is the most straightforward. You can access the property using square brackets [].

(click)="clickOnArea(item[language])"

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

Intellisense in VS Code is failing to provide assistance for data within Vue single file components

I am working with a simple code snippet like this However, within the method, the variable 'name' is being recognized as type any. Interestingly, when I hover over 'name' in the data, it shows up as a string. The Vetur plugin has alre ...

Using TypeORM to update a relation and set it to NULL

My challenge involves managing this specific Entity @Entity({ name: 'orders' }) export class Order { ... @ManyToOne(() => BulkOrder, (bulkOrder) => bulkOrder.orders) bulkOrder?: BulkOrder } In my update process, I am attempting to re ...

trouble with the layout of the table

Could you assist me in improving the design to enhance data clarity? Your help would be greatly appreciated. Thank you for your anticipated response. CSS File: table-layout: fixed; width: 100%; border-collapse: collapse; table-layout: fixed; ove ...

Matching the value of an Angular 4 FormGroup with an item in an array

In order to ensure that the input of the country in my form matches one of the countries in my predefined country list, I am looking to implement a custom validation function for my form group. Here is the list of available countries: this.sharedService. ...

Typescript types can inadvertently include unnecessary properties

It seems that when a class is used as a type, only keys of that class should be allowed. However, assigning [Symbol()], [String()], or [Number()] as property keys does not result in an error, allowing incorrect properties to be assigned. An even more curio ...

Applying the spread operator in the map function for copying objects

In my Angular application, I am attempting to copy an object and add a new property using the spread operator. To add the new property, I have created a method called 'addNewProperty(name)' which returns the property and its value. However, when ...

Mastering Inter-Composable Communication in Vue 3: A Guide

Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app. Discover More About Extracting Composables for Code Organization "Extracted composables act as component-scoped servi ...

Deleting an object from memory in Angular without destroying the component

I am facing a challenge with my complex Angular application as it is causing the browser to crash very quickly. Despite fixing memory leaks in every subscription, the issue persists. To optimize the app, I have resorted to using Chrome's debug module ...

Encountered a technical issue while attempting to assign a value in Angular

In my Angular application, I have defined an object called Task: export class Task { taskId: number; description: string; date: string; project: Project; } Within a component, I am working on implementing a method that will add a new task. To ac ...

Transferring Files with Cordova: Sending Images to Amazon S3

Currently, I am utilizing the ng-cordova file-Transfer plugin for uploading images to my AWS s3 bucket. During this process, I encountered two challenges - firstly, the plugin was not functioning as expected, and secondly, I struggled with debugging the i ...

Java Spark API using basic authentication will issue a 401 error response when accessed from an Angular application

My Java Spark API is set up for basic authentication. When I make a call to the URL from Postman with basic auth, it returns a JSON response. However, when I make the same call from an Angular 4 application, I get the error message: "Response for preflight ...

Challenges with Nested Reactive Form in Angular 4

I am utilizing Angular 4 reactive to develop nested forms. The structure of my forms is as follows: Form Group (userform) FormArray (users) FormGroup (idx) In the complete table, it falls under the Form Group. Each table row is a part of FormArray ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

Ways to bypass observance of an empty array?

I am utilizing the combineLatest operator: combineLatest(...this.filtersList.map((f) => f.filtersChanges)).subscribe((data) => { console.log(data); }); This operator retrieves the latest emitted changes in each stream - f.filtersCh ...

The process of sorting through an array of objects based on their specific types in TypeScript

I am working on a function that filters an array of objects based on their type property: export const retrieveLayoutChangeActions = (data: GetOperations['included']) => data.filter(d => d.type === 'layoutChangeAction') as Layou ...

Don't display div if database has certain value - Angular

Is there a way to determine if a specific value exists in a PostgreSQL database? If so, can I then hide an HTML element based on this information? Can CSS and JavaScript be used to hide elements, or is there another method that should be utilized for hidi ...

Guidance on specifying a type based on an enum in Javascript

I have a list of animals in an enum that I want to use to declare specific types. For instance: enum Animals { CAT = 'cat', DOG = 'dog', } Based on this Animal enum, I wish to declare a type structure like so: type AnimalType = { ...

Ensuring a User has an Image in MySQL Using Angular 6

As part of my development process, I am working on creating a new user and sending their information along with an image to a MySQL database. The process involves sending a user object with form data through the following component.ts file: subscribeUser() ...

Guide on utilizing async/await in .ts files (Encountering error message: "async functions can only be used when targeting ECMAScript 6 or above")

Initially, my project consisted of only app.js using ExpressJS as the main file with numerous lines of code. My development manager instructed me to refactor the code and move some functions into a separate .ts file (transition from JavaScript to TypeScrip ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...