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

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

Blueprint for constructing an optimal Angular and Spring Boot application.Creating a streamlined process for

I am currently working on constructing a spring boot/angular application. My goal is to run it locally in order to work on the front end login/logout process. To do this, I have angular set up to run on port 4200 and spring boot running on port 8080. How ...

Creating templates for both classes and individual objects is an essential part of object-oriented programming

I am working on a simple game project using TypeScript. My goal is to utilize interfaces to implement them in classes and pass them as arguments for creating new instances of a class. interface ObjectConstructor { element: HTMLElement; x_pos: numbe ...

Using aliases in npm packages is not supported

I am working on creating an npm package that I want to use in another application. During development, I set a path in tsconfig for importing various modules instead of using a relative path. However, when I download my package into the test app, it is una ...

"In Typescript, receiving the error message "Attempting to call an expression that is not callable" can be resolved

I am in the process of creating a function that matches React's useState signature: declare function useState<S>( initialState: S | (() => S), ): [S, React.Dispatch<React.SetStateAction<S>>]; Below is an excerpt from the functi ...

Steps to create a TypeScript function that mimics a JavaScript function

As I look at this javascript code: // find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' ...

The functionality of lazy loading and routing in Angular 10 appears to be malfunctioning

I recently attempted to implement routing and lazy loading in Angular 10.1.6, but for some unknown reason, I've encountered issues where the routing and lazy loading of a module simply isn't functioning as expected. Despite referring to the offic ...

Layout your Angular components with a column design using Flex Layout

Is there a way to adjust the width of a child component in an fxLayout set to column? Take this example for reference: https://stackblitz.com/edit/angular-fxlayout-custom-breakpoints?file=app%2Ftest.component.ts In the provided example, there are three f ...

How can I retrieve the current user in Angular with Firebase authentication?

Struggling with building an app using ionic v2 & firebase v3. Trying to access the logged-in user's details has been a challenge. In my app.ts, I successfully connect to my firebaseapp and recognize the logged-in user, leading them to the homepage: ...

"Implementing a Filter for Selecting Multiple Options in Ionic Framework

I need help with filtering books in an online library project using a modal page. The modal has 3 input fields for title, author, and year. How can I filter the books based on these inputs? Here is a snippet of my modal.html code: <ion-content pa ...

Tips for accurately defining the return type for querySelector(All) connections

I enjoy doing this particular task, ensuring the types are correct. const qs = document.querySelector.bind(document) as HTMLElementTagNameMap | null; const qsa = document.querySelectorAll.bind(document) as NodeListOf<any>; While hovering over query ...

Is it possible to insert data into SQL Server from an Angular application without relying on .NET Core?

Is there a way to extract data from an Angular-made form and store it in a SQL Server table without the need for .NET Core? ...

Is it feasible to restrict a generic type using typeguard?

I'm currently working on refining a generic function, where the autocomplete feature recognizes that it's encountering a typeguard, preventing it from revisiting the same code block. I suspect that the issue lies in not restricting the type to th ...

Primeng - Displaying names in editable datatable with multiSelect feature

Lately, I have been exploring primeng and I am interested in creating an editable table that includes a multi-select column. After some experimentation, I managed to achieve this result. However, my issue is that I want the winners field (which contains a ...

When utilizing Monggose, Angular, and Node, a route containing the deleteOne method repeatedly reports that the object has been successfully deleted, despite the delete count remaining

I've encountered a similar issue to others, but their solutions didn't work for me. I'm working on a small MEAN app with mongoose and facing a problem when trying to delete a user or any other object stored in the collection. The route seems ...

Could the "IonApp" class found in @ionic/angular (Ionic 4) be considered the updated version of the "App" class in ionic-angular (Ionic 3)?

I am currently in the process of upgrading an older Ionic app to Ionic 4. Previously, there were no issues before the migration I am working on a provider file helper.ts, and I have encountered a problem during the migration. Here is the output of ionic ...

Encountering Vue linting errors related to the defineEmits function

I am encountering an issue with the linting of my Vue SPA. I am using the defineEmits function from the script setup syntactic sugar (https://v3.vuejs.org/api/sfc-script-setup.html). The error messages are perplexing, and I am seeking assistance on how to ...

What is the process of inserting a sparkline chart into a Kendo Angular grid?

I am attempting to display a bullet chart in the first column of my grid. <kendo-grid-column> <ng-template kendoChartSeriesTooltipTemplate let-value="value"> <div> <kendo-sparkline [data]="bulletData" type="bullet" [ ...

Ensuring the inclusion of library licenses in the production build is a crucial step

We have numerous dependencies (node_modules) in our Angular app, which are typically licensed under Apache 2.0 or MIT. From my understanding of the licenses, the production build is considered a "derived work" and we are required to include copyright notic ...

RXJS: Introducing a functionality in Observable for deferred execution of a function upon subscription

Implementing a Custom Function in Observable for Subscribers (defer) I have created an Observable using event streams, specifically Bluetooth notifications. My goal is to execute a function (startNotifictions) only when the Observable has a subscriber. ...