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

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

Attempting to store the output of a function in a variable

My current script is designed to verify if the value of a selected element matches the span id. While the function itself functions correctly (verifying object.id via alert), I am encountering issues with variable assignment. When attempting to alert the ...

Using jQuery to iterate through an array and reverse its order

Is there a way to loop through an array and change the CSS background color chronologically rather than randomly? Additionally, is it possible to reverse through the same array when the back button is clicked? http://jsfiddle.net/qK2Dk/ $('#right&a ...

Enhancing Visual Studio 2017 with Docker Compatibility for Angular Applications

What is preventing the angular support from being available in VS 2017? Is there a missing component that is needed? https://i.stack.imgur.com/asJhO.png ...

jScrollPane malfunctioning with Bootstrap 3's dropdown menu

I'm attempting to add a vertical scrollbar to a Bootstrap dropdown. Below is the HTML code I'm working with: <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle btn_drop_down" data-toggle="dropdown"> ...

What is the best way to incorporate npm packages into my projects?

Lately, I've been heavily relying on nodejs, but I keep running into the same issue. With so many projects available and a plethora of npm packages to choose from, it's frustrating that every time I try npm install --save some-package, I struggle ...

Valid method of confirming a user's login status

Using AJAX requests, I have implemented a user area on my website. The "Log off" button is supposed to be displayed only when the user is logged in. Here is the AJAX request for logging in a user: function requestSI() { var xhr = getXMLHttpRequest(); xhr ...

Efficiently Populating Arrays Without Blocking

Let's dive into the scenario... Here is the template for our component <template> <div> <loader v-show="loading"></loader> // display loading animation <div v-show="!loading"> <div v-for="group in groups ...

The battle between HTML5's async attribute and JS's async property

What sets apart the Html5 async attribute from the JS async property? <script src="http://www.google-analytics.com/ga.js" async> versus (function() { var ga = document.createElement('script'); ga.type = 'text/javascript&apo ...

"The FindByIdAndUpdate function is successfully updating the data, but it is unexpectedly

This is my first time seeking guidance here, as I've reached a dead end with my issue. I am currently working on a household collection that includes a member collection within it. Whenever new members join, I need to update the household collection ...

Using Node.js to parse XLSX files and generate JSON output

Recently, I came across an extremely well-documented node_module known as js-xlsx Curious: How can I convert xlsx to json format? This is the structure of the excel sheet: The desired json output should resemble the following: [ { "id": 1, "H ...

Are there other options besides Chrome Frame for enhancing Raphael performance on Internet Explorer?

Currently, I am using Raphael 2.1 to simultaneously draw 15 lines, each consisting of 50 two-pixel paths. The performance is optimal in Safari and Chrome, acceptable in Firefox, subpar in Opera, and struggles in IE9. Despite Microsoft's claim that SVG ...

Guide on downloading a PDF file with NodeJS and then transmitting it to the client

My goal is to download a PDF file using NodeJS and then send its data to the client to be embedded in the page. Below is the code snippet I am using to download the PDF file: exports.sendPdf = function(req, responce) { var donneRecu = req.body; va ...

Having trouble with my jQuery .hover() code not running as expected

Whenever I hover over my divs, I want them to change color. However, the code doesn't seem to be working as expected when I try to do so. I suspect that the issue might be related to the z-index property used in the class that I am trying to hover ove ...

Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically: var URL = Xrm.Page.context.getClientUrl(); There are multiple instances within ...

Alter the arrow to dynamically point towards the location of the click source

I am currently working on creating a popover dialog that should point to the element triggering its appearance. The goal is for the arrow to align with the middle of the button when clicked. While I am familiar with using CSS to create pointing arrows, th ...

The class name is not defined for a certain child element in the icon creation function

Currently, I am developing a Vue2 web application using Leaflet and marker-cluster. I am encountering an issue with the iconCreateFunction option in my template: <v-marker-cluster :options="{ iconCreateFunction: iconCreateClsPrg}"> ...

My backend axios post request is not returning any data to my external API. What could be the issue?

I've encountered an issue where I'm attempting to transmit data from my client-side using an ajax call to my backend axios post request, which is responsible for posting data to an external API URL. Despite receiving a 200 status code, none of th ...

Rendering React component within a production build of Angular 7

I've been in the process of gradually moving an Angular app to React. After exploring options like single-spa and nx, I found that they weren't suitable due to the messy script-injected nature of the existing app. So, I decided to go for a semi-m ...

Creating an HTML string and then displaying its outer HTML in IE10 can be easily achieved. Just write the

My task is to write an HTML string to an element and then retrieve the resulting outer HTML from that element. This needs to be operational in IE10, latest versions of FF, Chrome, Safari, Android, iOS Safari but does not have to support any older browsers. ...