Strategies for navigating dynamic references in Angular 2 components

I am working with elements inside an ngFor loop. Each element is given a reference like #f{{floor}}b. The variable floor is used for this reference. My goal is to pass these elements to a function. Here is the code snippet:

<button #f{{floor}}b (click)="onClick(f{{floor}}b)"></button>

I attempted to do this, but it only passes a string like f5b instead of the actual element:

<button #f{{floor}}b (click)="onClick('f'+floor+'b')"></button>

Here is the full code snippet:

<div *ngFor="let floor of floors">
  <button #f{{floor}}b (click)="onClick('f'+floor+'b')"></button>
</div>

The variable floor is a number, and floors is an array of numbers.

Answer №1

It's perfectly fine to use the same template variable name within an *ngFor loop; there's no requirement to ensure unique template variable names inside the loop.

HTML Code

<div *ngFor="let item of items">
  <span #sp (click)="onClick(sp)"></span>
</div>

Even if you have identical template variable names, you can still access and manipulate the DOM elements using the @ViewChildren decorator.

@ViewChildren('sp') spanElements:QueryList<any>;

Answer №2

Utilize the identical variable

<div *ngFor="let level of levels">
  <button #btn (click)="onButtonClick(btn)"></button>
</div>

Alternatively, you can employ $event.target/currentTarget

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

Display conceal class following successful ajax response

Upon clicking the button, the following script is executed: $.ajax({ url: "<?php echo CHILD_URL; ?>/takeaway-orders.php", type: 'POST', async:false, data: 'uniq='+encodeURIComponent(uniq)+'&menu_id=' ...

"Enhance readability by adjusting the font size on mobile devices and iPhones for an

I'm currently working on a website that needs to maintain a consistent look across all types of devices, including laptops, PCs, iPads, iPhones, and other smartphones. To achieve this, I've implemented fittext.js, a pure JavaScript solution that ...

Every row within the data grid component must contain a distinct `id` property

How do I utilize statId instead of id in my code? Should I create a unique id property for each row? Error: MUI: All rows in the data grid component must have a distinct id property. Alternatively, you can define a custom id using the getRowId prop. A ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

IE may not support the use of XMLHttpRequest with the POST method

When interacting with a server through an XMLHttpRequest to post data, the code typically follows this structure: var xhr = new XMLHttpRequest(); var url = 'http://myurl/post'; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", " ...

Having trouble modifying the fields in the formArray

https://i.sstatic.net/B4uTq.pngWorking with reactive forms, I have a UI feature that displays radioButton options which, when selected, reveals details about the chosen value within the form. Once a button is selected, the form fetches data from the backen ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

Connected Date Selector

I am new to using Bootstrap and attempting to implement a linked datepicker with the following requirements: Display only the date (not the time). The default selected date on page load should be today's date for both the Datepicker and the text ...

Troubleshooting issues with setting errors on a FormGroup instance in Angular Reactive Forms are proving to be more challenging

Currently I am working with Angular 4.4.3 reactive forms to create custom validation for a group of controls within a form. As per the documentation on AbstractControl.setErrors, this method updates the errors property of the AbstractControl that it's ...

AngularJS directive facing a callback problem

Having trouble with callbacks while calling a service function This is the function defined in registrationService function checkUserAccess(incentiveLevel, callback, displayRegistrationView) { var url = "..."; httpWrapperService. ...

How can I use JavaScript to retrieve the current time from the time.nist.gov NTP server?

Looking for guidance! I'm new to coding and would greatly appreciate detailed instructions and examples. I've been struggling for hours trying to solve this issue - the online resources I found have not been helpful at all. Unfortunately, I don&a ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Angular - Implementing filter functionality for an array of objects based on multiple dropdown selections

I am currently working on filtering an array of objects based on four fields from a form. These four fields can be combined for more specific filtering. The four fields consist of two dropdowns with multiple selection options and two text boxes. Upon cli ...

Tips for storing the device token received from Firebase Cloud Messaging in an Ionic2 application

Using the FCM plugin for ionic2, I was able to successfully implement push notifications. For reference, you can check out the plugin here. I followed the steps outlined in this Github repository, and everything is working smoothly so far. Now, my next go ...

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...

Enhance the axis functionality in c3.js

My goal is to display a user's financial data for the previous week, but sometimes they may not have data for all seven days. When using c3.js, I noticed that it automatically extends the 'endpoint-value' to the end of the axis. Is there a w ...

An issue occurred while testing with React-Native Testing Library/Jest, where the property 'TouchableOpacity' could not be read

I am currently in the process of conducting tests using jest and react-native testing. Unfortunately, I have encountered an issue where TouchableOpacity is not being recognized and causing errors. Card.test.js import Card from "../Card" import R ...

Difficulty sending a parameter to the onClick function of a React Button

I'm struggling with passing parameters to my callback function when clicking a material-ui button. Unfortunately, the following approach is not yielding the expected results. const fetchData = async (param) => { } <Button onClick={fetchData(&a ...

Getting access to a child component function within the UI-VIEW in Angular 2

I am working on a project that involves both angular 1.5 and angular 2. In my project, I have two sibling components: First-component and Second-component. The First-component contains a Toggle button, while the Second-component has a UI-View of angular 1. ...

Utilizing TypeScript's higher-order components to exclude a React property when implementing them

Trying to create a higher-order component in TypeScript that takes a React component class, wraps it, and returns a type with one of the declared properties omitted. Here's an attempt: interface MyProps { hello: string; world: number; } interfac ...