Reactive form in Angular 11 returns null for dynamic values

After creating a reactive form in Angular, I fetched some fields from the backend and applied them to an input type hidden field. The value of this field will not change, but when I try to insert this value into the database, it returns null in the console. However, in the developer tools, it shows the correct value. Here is the code snippet:

Inside discussion.component.html file:

<form [formGroup]="pollResult">
  <input type="hidden" value="{{pollQuestion?.id}}" formControlName="pollQuestionId">
  <input type="hidden" name="userId" value="1" formControlName="userId">
  <div class="radio-group">
    <label class="container" *ngFor="let item of pollQuestion?.CM_Poll_Options;let i=index"
    > {{item.pollOption}}
      <input type="radio" checked="checked" name="pollOption" value="{{item.id}}" formControlName="pollOption"/>
      <span class="checkmark"></span>
      <small>60%</small>
      <div style="width: 60%"></div>
    </label>

  </div>
  <button type="submit" class="submit_vote" (click)="submitPoll(pollResult.value)">
    Submit your vote
  </button>
</form>

Inside discussions.component.ts file:

this.pollResult = this.fb.group({
   pollQuestionId:[''],
   userId:[''],
   pollOption:['']
});

In the above code snippet, the pollOption value works fine, but the pollQuestionId and userId return null instead of the value applied in the value attribute.

Answer №1

Unbind the value property association

  <input type="hidden" formControlName="pollQuestionId">
  <input type="hidden" name="userId" formControlName="userId">

In your TypeScript file, assign values to these controls

ngOnInit() {
  this.myService.getData().subscribe({
    next: (pollQuestion) => {
      this.pollResult.get('pollQuestionId').setValue(pollQuestion?.id);
      this.pollResult.get('userId').setValue(1)
    }
  })
}

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

Is it possible to run tsc on a whole directory in Typescript?

It's quite interesting that I couldn't find this information in the documentation - is there a simple way to instruct tsc to compile all files within a directory and its subdirectories without setting up a complete tsconfig.json configuration? ...

Proceed with the for loop once the observable has finished

Currently, I have a situation where I am making an http.get call within a for loop. The code is functioning correctly, but the issue lies in the fact that the loop continues to iterate even if the observable is not yet complete. Here is the snippet of my ...

Error encountered while loading GitHub Pages resource

Currently, I am facing issues while attempting to host an Angular application with Bootstrap 4 on GitHub Pages using angular-cli-ghpages. The URL I am trying to deploy it at is , but I continuously encounter the following error: Failed to load resource: s ...

Utilizing Angular HTTP Interceptor to Show Loading Spinner Across Multiple Modules

My goal is to utilize the ng4-loading-spinner spinner when making HTTP calls to my API. I referred to the examples provided in the following resources: Angular Guide on Intercepting HTTP Requests/Responses Stack Overflow Post on Using HttpClient Interce ...

Leverage AngularCLI to create components for projects containing multiple apps

In my current project setup, the configuration in my .angular-cli.json file is structured as follows: { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "project": { "name": "suman-chrome-extension" }, "apps": [ { "r ...

Inject the data within Observable<Object> into Observable<Array>

I'm faced with a situation where I have two distinct API endpoints. One endpoint returns a single Card object, while the other endpoint returns an Array of Card objects. My goal is to retrieve the first Card from the single Card endpoint and place it ...

Validation Limit upto 30 days (Angular version 4 and above)

I am currently facing an issue with validation limiting to one month. I would like the Date validation to be restricted to a maximum of one month. Below is my validation function: public minmonthValidator() { let value = true; let endDate = t ...

Setting up a route based on URL parameters from various applications

My Java application has 5 links, and I want each link to open a specific Angular form based on the parameters passed through them. How can I configure my routes in Angular to achieve this functionality? ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

Navigating back to a specific segment of a dataset while using virtual scrolling

Virtual scrolling is a fantastic way to optimize rendering for large data sets. For this particular scenario, I am making use of the Angular Material CDK APIs to implement this feature. However, a specific requirement needs to be addressed - when a user ...

Prevent special characters in input fields using Angular and TypeScript

I am currently working on an Angular project using Ant Design ng Zorro. I've encountered an issue with validation when trying to restrict special characters in an input field. Despite setting up the validation rules, it seems that the key press event ...

Using Redux in combination with Firebase authentication

I'm currently working on implementing authentication in my React application using Redux with Redux Toolkit. Here's what I have so far: I've created a sign-in function utilizing createAsyncThunk export const signin = createAsyncThunk( &ap ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

What sets apart formControl.hasError('required') from formControl.errors?.['required']?

I have an Angular reactive form and I've come across two different approaches in the forums. Some suggest avoiding function calls in the template. Can you explain the difference between these approaches and which one is considered best practice? <m ...

What could be causing the malfunction of my button's event handlers?

Users can fill out a form in which they provide information about a grocery item they want to add to their cart. After completing the form, they can click on the "Add Item" button. Here's the form in my app.component.html: <form (ngSubmit)="a ...

Ways to ensure the React prop type matches the value provided when using typescript?

Within my List component, there are 2 props that it takes in: items = an array of items component = a react component The main function of the List component is to iterate over the items and display each item using the specified component. // List ...

What could be causing the type error in TypeScript that WebStorm is displaying?

Currently, I am immersed in a Nextjs project utilizing <span class="__cf_email__" data-cfemail="83c0ebe2f1f7ade9f0c3b7adb0adb3">[email protected]</span> and <span class="__cf_email__" data-cfemail="b5c7d0d4d6c198d6ddd4c7c1dfc69887f5809b ...

Tips for resolving the error message "Cannot use type '{}' as an index type"

interface TicketTime { startTime: string; endTime: string; } interface TicketInfo { id: number; from: string; to: string; company: string; price: number; time: TicketTime; duration: number; connectionAmount: numb ...

Adjusting the height of a div element when scrolling

Is there a way to make a div change size as you scroll? I am trying to achieve an effect like this example: . Currently, I am using Angular's hostListener to capture scroll events and adjust the div accordingly. However, I have been experiencing some ...

instructions on activating previous and next button in pagination using material angular

In my exploration of material angular pagination, I encountered an issue where the pagination buttons get disabled when retrieving data in chunks from the backend. For instance, with 7 records and a table set to display 5 items on the first page and 2 on t ...