Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I prevent this and ensure each field behaves independently?

Below is the code snippet I have so far:

Here's my JavaScript function:

function takePictureFromCamera(ven) {
  let options: CameraOptions = {
    quality: 15,
    destinationType: camera.DestinationType.FILE_URI,
    encodingType: camera.EncodingType.JPEG,
    mediaType: camera.MediaType.PICTURE,
    sourceType: 1,
    cameraDirection: camera.Direction.BACK
  }

  camera.getPicture(options).then((imageData) => {
    console.log('imageData: ', imageData);
    this.imageData = normalizeURL(imageData);
    console.log('normalized imageData: ', this.imageData);

    var venName = ven.vendor;
    
    var tok = localStorage['token'];
    

    const fileTransfer: FileTransferObject = transfer.create();
    var total = parseFloat(this.inputVen);

    let options1: FileUploadOptions = {
      fileKey: 'slip',
      fileName: 'name.jpeg',
      chunkedMode: false,
      mimeType: "image/jpeg",
      headers: { 'token': tok, 'vendor': venName, 'total': total }
    };

   
    fileTransfer.upload(this.imageData, 'http://192.168.0.7:8080/static/images/ionicfile.jpg', options1)
      .then((data) => {
        console.log(JSON.stringify(data) + " Uploaded Successfully");
        

        console.log(data);

        let alert = alerCtrl.create({
          title: JSON.stringify(data),
        });
        alert.present();

        this.inputVen = '';

      }, (err) => {
        console.log(err);

        let alert = alerCtrl.create({
          title: JSON.stringify(err),
        });
        alert.present();

      });
  }, (err) => {
    console.log('error: ', JSON.stringify(err));
  });
}
And here's the HTML template:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.11/angular.min.js"></script>
<table>
   <tr >
      <th>Vendor Name</th>
      <th>Total</th>
      <th>Slip</th>
   </tr>
   <tr *ngFor="let ven of VendorsS">
      <td> {{ven.vendor}}
      </td>
      <td ><input type="type" placeholder="Total" [(ngModel)]="inputVen" size="6px"/></td>
      <td>
         <button (click)="takePictureFromCamera(ven)">
            <ion-icon ios="ios-camera" md="md-camera"></ion-icon>
         </button>
      </td>
   </tr>
   <tr>
</table>

Answer №1

The issue arises from binding each input in the *ngFor loop to the same value in the model, namely inputVen. It appears unclear what your intention is based on the provided example, but I presume you aim to update the total property of the vendor.

Consider binding to ven.total (or the relevant property of ven that requires updating) rather than inputVen.

<tr *ngFor="let ven of VendorsS">
  <td> {{ven.vendor}}
  </td>
  <td ><input type="type" placeholder="Total" [(ngModel)]="ven.total" size="6px"/></td>
  <td>
     <button (click)="takePictureFromCamera(ven)">
        <ion-icon ios="ios-camera" md="md-camera"></ion-icon>
     </button>
  </td>

In your script file, utilize ven.total instead of referencing inputVen;

var total = parseFloat(ven.total);

Answer №2

Here are some steps you can take:

  • Convert your inputVen into an array of values;

  • Update your *ngFor with the following code:

   <tr *ngFor="let ven of VendorsS; let i = index">
      <td> {{ven.vendor}}
      </td>
      <td ><input type="type" placeholder="Total" [(ngModel)]="inputVen[i]" size="6px"/></td>
      <td>
         <button (click)="takePictureFromCamera(ven)">
            <ion-icon ios="ios-camera" md="md-camera"></ion-icon>
         </button>
      </td>
   </tr>

Remember, you can access the index in the for loop using "let i = index". This allows you to bind multiple elements to the TypeScript array. For more information on ngFor syntax, check out: Hope this explanation is helpful.

Answer №3

If you want to modify the template to utilize the index obtained from ngFor, you can bind an array (using the index) in NgModel and then adjust the component to create inputVen as an array with a specified length.

//template
<tr *ngFor="let ven of VendorsS; let i = index">
    <td> {{ven.vendor}}
    </td>
    <td ><input type="type" placeholder="Total" [(ngModel)]="inputVen[i]" size="6px"/></td>
    <td>
        <button (click)="takePictureFromCamera(ven)">
        <ion-icon ios="ios-camera" md="md-camera"></ion-icon>
        </button>
    </td>
</tr>

//component
inputVen = []
...
this.inputVen = Array(this.VendorsS.length)

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

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...

Guidelines on maintaining an active getSelection with JavaScript

I need help figuring out how to change the font size of selected text within a div without losing the highlight/selection when I click a button. Can someone assist me in keeping the text highlighted while also resizing it upon clicking the button? ...

What are the steps to automatically populate the location or name in the trip advisor widget?

I have encountered an issue with my website where I have multiple hotel lists but the trip advisor widget only shows one. Is there a solution, such as a script or other method, that can use variables to automatically set the location or name in the widget? ...

Using AngularJS: The ultimate guide to invoking a service within a module

I have a controller that successfully calls a service. However, I now need to access a method within that service from another module. How can I achieve this? BaSiderbarService: (function() { 'use strict'; angular.module('BlurAdmi ...

Is it time to execute a mocha test?

Good day, I am currently exploring the world of software testing and recently installed Mocha. However, I seem to be encountering an issue with running a basic test that involves comparing two numbers. Can someone please guide me on why this is happening a ...

After the transition to Angular 8, the functionality of testing with Jest seems to have

After upgrading our Angular version from 7 to 8, we encountered some issues when using Jest as our test runner. Our main objective now is to ensure that our build pipeline runs smoothly with our JavaScript tests. One error message we're facing is: An ...

"Deploying code to Heroku using Node.js: A guide to adding git commits directly on

Currently, as I delve into learning Node and Git, I'm faced with a dilemma involving my Heroku app. The app is designed to interact with a local file on the server that serves as a basic JSON database. The issue arises when I attempt to manage this f ...

Troubleshooting error "is not assignable to type..." when simulating global fetch using TypeScript

I am encountering an issue with the "global.fetch" part and cannot seem to figure out why. Despite following the standard procedure, I am still facing this TS2322 error. I am seeking assistance to understand why this error is occurring. I am open to sugges ...

Using jQuery UI datepicker - how to set a parameter based on a specific condition

New to the world of JavaScript, I am trying my hand at implementing the jQuery UI datepicker widget. My goal is to add an additional line to the widget parameters if the variable selectedDate has a value. However, my current approach seems to be ineffecti ...

Tips for capturing your desktop screen within an angular 2+ application

I am in need of a solution to share my desktop screen using Angular 6. I have done some research to find the right package for this feature but have been unsuccessful so far. I came across various packages such as RecordRTC, Aperture, and screen-capture-r ...

Disabling FormArray on-the-fly in Angular

I have a scenario where I need to disable multiple checkboxes in a FormArray when the page loads. Despite my attempts to implement this, it hasn't been successful so far. Can someone provide guidance on how to achieve this? .ts file public myForm: Fo ...

What is the best way to display each value from the array arr, containing strings, on separate lines?

Can you complete the function below to display each value in the array 'arr' on separate lines? <!DOCTYPE html> <html> <head> <title> ...

Error with application tab directive based on user roles

My custom directive, the `has-role.directive.ts`, is responsible for displaying or hiding tabs in my application based on the user's role. However, I encountered an issue where after logging out, the directive fails to update the view and the tab rema ...

A new issue arises after merging in Google Datastore, as an unexpected property is

Currently, I am working on developing an API in Typescript to interact with a Google Cloud Datastore instance for storing and retrieving entities. So far, I have successfully implemented the GET, POST, and DELETE methods. However, I encountered an issue w ...

Simulated alternate identities for UI Router

I am managing a group of pages/URLs that share a common parent state/template: /orders/list /orders/create /products/list /products/create Currently, I have two dummy states/routes (/products and /orders) that serve as parent states for the other substat ...

Create a circle surrounding the latitude and longitude on a Bing Maps angular display

I successfully integrated the Bing map with Angular using the angular-map package, and now I want to draw a circle around a given latitude and longitude. To achieve this, I installed the following npm packages: npm install --save angular-maps npm ins ...

Encountering a problem with GraphQL API fetching in Next.js: receiving the error message "React functionality 'useContext' is not supported in this environment."

Currently, I have developed a Next.js 14.2.3 application with a GraphQL API endpoint (which I replaced with localhost for StackOverflow). For data fetching, I am utilizing "@apollo/client": "^3.10.3" and "graphql": "^16.8.1". The product page path has been ...

Is there a method to incorporate lists of varying types in a single v-for loop without causing any issues with type validations?

My current component is designed to display two different datasets, each with their own unique nature of data: state.articleTypeList: string[] state.renderPriceClassNameList: {[key: string]: string[]} To render both datasets within a single v-for componen ...

Exploring Angular 17's unique approach to structuring standalone components

Is something wrong with my code if I can only see the footer, header, and side-nav components on localhost? How can I fix this? app.component.html <div class="container-fluid"> <div class="row"> <div class=&q ...

Bespoke search functionality using AJAX and tags in WordPress

I have created a custom search form in my WordPress theme that looks like this: <form role="search" class="form" method="get" action="<?php echo home_url('/');?>"> <input type="search" id="keyword" class="inp-search" onclick="sh ...