Retrieve the value of a hidden input when a button is clicked using reactive forms in Angular

I am currently attempting to retrieve the values of hidden input fields that are dynamically added when the user clicks on the "insert more" button.

If you'd like to view the code in action, you can visit this StackBlitz link: get hidden input value

I have tried using the patchValue() method within the linkTo() function, but unfortunately, I am encountering an issue where the console displays empty strings upon clicking the "Get Values" button.

Console Output:

loginFromArr: Array[2]
0: Object
name: "p1"
password: "p235"
selectedLinkTo: ""
1: Object
name: "876548"
password: "43545t"
selectedLinkTo: ""

As you can see, the value for selectedLinkTo is empty in the console output.

Answer №1

I tried implementing some code and included the value in the SelectLinkTo.

linkTo(where: string, btnId: number) {
    console.log(btnId);    
    let formArray = (<FormArray>this.loginForm[this.currentTab].get('loginFromArr')).at(btnId)
    console.log(formArray);
    formArray.patchValue({
        selectedLinkTo :where
    })    
}

To perform validation, you can use the code below:

printCurrentTab() {
 if(this.loginForm[this.currentTab].valid) {
  console.log(this.loginForm[this.currentTab].getRawValue());
 }else{
  console.log("Please fill the required fields")
 }
}

Additionally, to add a new row, you can include the following function:

addMore() {
  if(this.loginForm[this.currentTab].valid) {
    this.loginFromArr.push(
      this.fb.group({
        name: ["", Validators.required],
        password: ["", Validators.required],
        selectedLinkTo: ["", Validators.required]
      })
    );
  } else {
    console.log("Please fill the required fields")
  }
}

Using these codes will help with the validation process.

Answer №2

To pass a form and set the control value, you can simply follow this approach.

<a style="border: 1px solid red;margin-top: 10px; margin-left: 5px;" id="a-{{i}}" 
  (click)="linkTo('a',item)" 
   class="btn-link-group border-right-0 first-btn"
mat-button>A link</a>

linkTo(where: string, form: any) {
    //debugger;
    form.controls['selectedLinkTo'].setValue(where);
  }

For a live demo, you can visit - https://stackblitz.com/edit/get-dynamic-added-component-values-fecshe

Hopefully, this solution proves to be beneficial to you.

Answer №3

function updateLink(whereTo: string, buttonId: number) {
this.loginForm[this.currentTab].get('loginFromArr').controls[buttonId].get('selectedLinkTo').setValue(whereTo);}

Kindly update your code with the function provided above.

Answer №4

snippet for linkTo function patchValue():

linkTo(destination: string, buttonId: number) {
        let formArray = this.loginForm[this.currentTab].get('loginFromArr').at(buttonId)
        formArray.patchValue({
            selectedDestination: destination
        })  
}

Try out the demo here: https://example.com/demo

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

Failure during building Angular 13 library with Ivy partial compilation mode

Recently, I encountered an issue while trying to install an npm package that utilized node-gyp. In an attempt to resolve the problem, I upgraded my Node.js minor version from 16.13.0 to 16.13.1 and also updated my Angular CLI from 13.0.2 to 13.2.0. After ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...

In order to conceal the div tag once the animation concludes, I seek to implement React

I'm currently using the framer-motion library to add animation effects to my web page. I have a specific requirement where I want to hide a div tag used for animations once the animation is complete. Currently, after the animation finishes, the div t ...

How can input be prevented on keydown within angular6?

Is there a way to disable the input field only when a keydown event occurs, without affecting other input fields? xyz.component.html <input type="text" (keydown)="disableInput($event)"> // <-- Disable if keydown <input type="text" (keydown) ...

Diverse Templates within a Single Angular Component

Is there a way to reuse a single component with varying content? I have a component called quick-links that extends the dashboard-panel component and includes a title and content. I am looking to reuse the quick-links component with different titles and co ...

Tips for setting up nested folders using Node.js on a Windows machine:

Is there a way to use Nodejs in Windows 10/11 to create a parent folder and then add a new folder inside of that parent folder, like this: parent/child within the Documents folder? ...

Issue with forRoot method not triggering within Angular library

I have developed an Angular library with a static forRoot method to transfer static data from the application to the library. The purpose of creating a forRoot method is to effectively manage this process. export class DynamicFormBuilderModule { public s ...

Automate the selection of an item in a Primeng Listbox using Angular 2 and PrimeNg

After displaying a list using a PrimeNg Listbox (p-listbox), I needed to monitor the changes in selection by implementing the ngDoCheck lifecycle hook. Specifically, I wanted to detect when the user selected a specific group ("Group0") and then revert the ...

Adjusting canvas height in Storybook - Component does not fit properly due to low canvas height

I had a component that I needed to add to Storybook. It was working fine, but the styling was slightly off. I managed to resolve this by adding inline styling with position: absolute. Here is how it looks now: const Template: any = (args: any): any => ( ...

Angular provides the capability to sort through data using various criteria

I have received an array of objects in a specific format from the server, which may contain more than 2 objects. [ {processId : 1, processName : "process1", country : "germany", companyCode:"IB" , companyHiringType:"FRE", masterClauses:[ {cl ...

Adding a CSS class to a component element

I am working with an angular component that looks like this: export class HeaderMainComponent { } This is the HTML structure: <header> <nav> <li>Link 1</li> <li>Link 2</li> </nav> </header> ...

Using react-hook-form to easily update form data

While working on my project with react-hook-form for updating and creating details, I encountered a problem specifically in the update form. The values were not updating properly as expected. The issue seems to be within the file countryupdate.tsx. import ...

Having trouble with your React/TypeScript/Redux/Thunk action not dispatching and the state remaining unchanged?

Currently, I am facing an issue while attempting to send a GET request to an API using React-Redux & TypeScript. The goal is to dispatch an action upon clicking a button (onClick event), make the request, update the state via the reducer, and finally log t ...

I need a way to call a function in my Typescript code that will update the total value

I am trying to update my total automatically when the quantity or price changes, but so far nothing is happening. The products in question are as follows: this.products = this.ps.getProduct(); this.form= this.fb.group({ 'total': ...

Upon attempting to open Google Maps for the second time, an error message pops up indicating that the Google Maps JavaScript API has been included multiple times on this page

Currently, I am utilizing the npm package known as google-maps and integrating it with an angular material modal to display a map. However, upon opening the map for the second time, an error message is triggered: You have included the Google Maps JavaScri ...

Enhance Your GoJS Pipeline Visualization with TextBlocks

I am facing challenges in customizing the GoJS Pipes example to include text within the "pipes" without disrupting the layout. Although I referred to an older response on the same query here, it seems outdated or not detailed enough for me to implement wit ...

What is the proper way to type the SubmitEvent so that the event.target.children property can be accessed

Below is the form I currently have: <form id="search" method="post"> <input type="text" name="query" id="search-field"/> </form> I am looking to add a submit event listener in TypeScript: ...

Develop a module using the Angular plugin within the Eclipse IDE

I am currently new to Angular and following the Angular Get Started Tutorial (https://angular.io/guide/quickstart). I am using the angular cli plugin in Eclipse. As I reached the 7th part of the tutorial, I am required to create a new module with the comm ...

Setting a default value for a select option in Angular 2

I am trying to set a default value for an option, acting as a placeholder using this method. It works in pure HTML, but when I implement it with the *ngFor attribute in Angular 2, nothing is selected. Here is the code I use in pure HTML: <select name= ...

"Overcoming obstacles in managing the global state of a TypeScript preact app with React/Next signals

Hello, I recently attempted to implement a global app state in Preact following the instructions provided in this documentation. However, I kept encountering errors as this is my first time using useContext and I suspect that my configuration might be inco ...