One-of-a-kind data connection

I'm facing a challenge with data-bindings that I can't quite crack. It seems like my lack of expertise in the Angular domain might be the root cause.

If you have a solution, I would greatly appreciate it if you could provide a brief explanation as well.

The Problem:

I have a table where I use *ngFor to list all users from my data object. Each user has a collapsible section for editing, which includes "password" and "repeat password" fields.

Next to the "password" field, there is a button labeled "Generate" that triggers a function to generate a random password string.

My problem is that when I generate a new password, it updates the variable used for data-binding in every row of the table. I want each generated password to remain unique to its corresponding input field.

Pictures:

--------------------------------------------------------------------------- separate

Code:

manage-user.ts:

export class ManageUserComponent {
private updatedUserPassword: string;

private usersData: Object[] = [
    { userID: '1',  firstName: 'Name0',  lastName: 'lastname', username: 'user01@example.com', teamName: 'randomteamname',  teamID: 1 }, 
    // other user data entries...
];

// Other code snippets are available in the original question.

manage-user.html:

<div class="form-group col-lg-6 col-md-6 col-sm-6">
  <div class="form-group">
        <label>New Password</label>
        <div class="input-group">
              <input type="text" class="form-control" ngControl="edit_password" [(ngModel)]="updatedUserPassword" placeholder="Enter New Password">
              <span class="input-group-btn">
                    <a (click)="generatePassword()" class="btn btn-primary">Generate</a>
              </span>
        </div>
  </div>

Answer №1

Check out this functional code

To solve your issue, make sure to assign a unique ngModel for each row when using the ngFor loop.

The problem you encountered was that updating the password affected all rows simultaneously. To prevent this, ensure that each row has its own specific ngModel, as mentioned earlier.

I've created a modified version of your code in this functional example. Although it doesn't include the entire code, it should give you an idea of what changes were made. Pay attention to [(ngModel)]="updateUserPwd".

If this solution aligns with your requirements, please let me know.

<div class="form-group col-lg-6 col-md-6 col-sm-6">
      <div class="form-group" *ngFor="#item of users;#i=index">
            <label>New password {{i}}</label>
            <div class="input-group">
                  <input type="text" class="form-control"  [(ngModel)]="item.updateUserPwd" placeholder="New Password">
                  <span class="input-group-btn">
                        <a (click)="generatePassword(i,item)" class="btn btn-primary">Randomize</a>
                  </span>
            </div>
      </div>
</div>

private generatePassword(i,item):string {   <------this is single object from ngFor which you want to update.
    console.log('started' + i );
    console.log(item);
    var length = 8,
        charset = "ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",
        retVal = "";
    for (var i = 0, n = charset.length; i < length; ++i) {
        retVal += charset.charAt(Math.floor(Math.random() * n));
    }

    item.updateUserPwd=retVal;  <------ this is important. This will change/update individual object property that you want to update. 
  }
}

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

Utilize ng-src in an Angular image tag when iterating through ng-repeat items

Using ng-src on img tags within ng-repeats has been successful for me in the past, but I'm facing difficulties with it this time. After making an API call that returns some data, I tried to display each item like this: <div ng-repeat="item in ...

The sorting feature of the ng-table is malfunctioning

I am trying to achieve the following display: When clicking on a column header(th), I want to be able to sort my table. However, I am having trouble using the ng-table component with my data structure. The table is displaying correctly but the sorting fun ...

Unable to bring in personalized typescript package in node.js

After struggling for hours trying to figure it out on my own, I finally decided to seek help on stackoverflow. I have a custom typescript project/package that I want to use with zx. I packed it using npm pack and installed the tar.gz globally. However, whe ...

Tips for handling numerous buttons in ionic?

I'm currently working on an app that includes surveys. In this app, users are required to answer by selecting either the Yes or No button. The desired behavior is for the chosen button to turn blue once clicked, while the other button should maintain ...

ionChange - only detect changes made in the view and update the model in Ionic 2

In my Ionic 2 application, I have a feature that allows users to schedule notifications as reminders. The requirements for this feature are as follows: Upon entering the reminder page, it should check if there is a saved reminder. If a reminder is saved ...

The HTTP request fails to accept the input value provided

Visual Representation of File Structure https://i.sstatic.net/6nscS.png export class FaqService { public inputValue; constructor(private http: Http) {} ngOnInit() {} setData(val) { this.inputValue = val; console.log(this.inputValue); } getData() ...

Alter the data displayed by the Radio button using Angular when the Submit button is clicked

I've encountered an issue where I need to alter a div based on the selection of a radio button. Currently, it changes instantly upon button click, rather than waiting for submission. My desired outcome is for the value to be submitted when the button ...

Developing an Angular feature that creates a live status feed by calling a web service

Being new to Angular, I am still trying to grasp the concept of subscriptions and observables. I have a webservice that returns a status object that my website needs. The webservice keeps the connection open for 30 seconds, closes it if there is no new dat ...

Changing icons within an ngFor loop in Angular 2

Looking for a solution: How can I toggle icons using ngFor? Situation: I am using *ngFor to iterate through an array and display category names. When a day is clicked, I want to open an accordion and show category details (which I have already managed). O ...

Master the art of animating ng-view transitions with AngularJS

I have 2 distinct HTML pages, namely welcome.html and login.html. These two pages are incorporated or "inserted" into a common page called index.html through the utilization of an exclusive attribute known as ngview, together with a router provider. This i ...

Step-by-step guide on incorporating edit, update, and discard functionalities within an Angular Material table component (mat-table)

I am currently working on implementing edit, update, and discard functions in an angular material table. While I have been able to successfully edit and update the table row wise, I am struggling with how to discard table rows. If you would like to see wh ...

Tips for triggering multiple components in Angular2 with a single event

My current project involves an input component, an output component, and a processing service. The goal is to allow the user to input a string, have it processed by the processing service, and then display the processed message in the output component. How ...

Passing Optional Parameters to AngularJS Modal

Is there a way to pass an optional parameter to my angularJS modal? Let's take a look at the code: TRIGGER CONTROLLER: $modal.open({ templateUrl: 'UploadPartial.html', controller: 'photos.uploadCtrl', resolve: { presele ...

Retrieve an element from a child directive within the parent directive

Is there a way to retrieve the element with the class name .second from the second directive in the link function of the first directive? Click here P.S. I have tried it with the template in the link functions, but I specifically need to use templateUrl. ...

Common Errors in Angular 2 due to TSLint

I am encountering multiple errors in my code. I am using Angular 2 with TSLint: constructor(http: Http) { this.http = http; --> let currentUser = JSON.parse(localStorage.getItem("currentUser")); this.token = currentUser && currentUser.t ...

Obtaining API/JSON Data to Implement in a NextJS Application

Currently, I am working on developing a NextJs website that focuses on detecting crop diseases. The process involves sending photos and environmental data to a fastapi python server for processing. Subsequently, the processed data is supposed to be display ...

Best practice for retrieving an object by its unique ID within an array of objects in Angular 2?

I am dealing with two arrays: categories and articles. Here is a visual representation of the arrays: categories = [{id: 1, name: 'Gadgets'}, {id: 2, name: 'Artificial Intelligence'}, {id: 3, name: 'Opinions'}]; articles ...

How can I execute a TypeScript / TSX file from a Next.js project in the terminal using ts-node?

One of my go-to tools is ts-node for running individual files. I'm currently attempting to execute files like ts-node ./page/home.tsx, but I'm encountering issues within my Next.js project. export const WidgetList = createWidget<ButtonListPro ...

The routerlink feature consistently directs back to the default page

I am facing an issue where my routerlink does not redirect me to the correct path in app.routes.ts when clicked. Even though the routerlinks are set as 'user/teams' and 'user/dashboard' respectively. I can access the pages by directly ...

Prevent the array from altering its values

I am utilizing a mock-service that is configured in the following way: import { Article } from "./article"; export const ARTICLES: Article[] = [ new Article( 1, 'used', 5060639120949, 'Monster Energy& ...