manikandan
manikandan

Reputation: 815

Dynamic value return null in reactive form using Angular 11

I have created reactive form in angular, have fetched few fields from backend and applied in input type hidden field its value will not change. i need to insert the value to database. but the value return null in console but in developer tools its showing correct value. kindly find the code below

in 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>

in discussions.component.ts file

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

in the above code pollOption value working fine and pollQuestionId and userId returns null not return the value which is applied in value attribute.

Upvotes: 1

Views: 915

Answers (1)

Owen Kelvin
Owen Kelvin

Reputation: 15083

Remove the binding to the value property

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

In your TS, set the value of this controls

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

Upvotes: 1

Related Questions