Search code examples
htmlangularformsangular-formsngmodel

Automatically Insert static value into textbox based on radio selection?


All of the values in the textboxes are saving correctly into the database except remark field which is displaying null. From my shared codes below, when l checked on score radio button, remark textbox value is updated to 5 and when l clicked on save button all the input data are saved except remark column showing null in the database.

group1 textbox

Textbox1          Textbox2        Textbox3
Name= 'Horse',    Score= '1',      Remark= '5'

Below is codes that l had tried

component.ts

onSubmit(form: NgForm){
this.service.formSubmitted = true;    
//Group1
if (form.valid) {
  this.service.postgroup1()
  .subscribe({next: res => {        
    console.log(res);
  }})
}    
else {
  this.toastr.error('Please Enter Your Data ');
  }
}  

selectedValue1: string = '';

onRadio1(event: any): void {
 this.selectedValue1 = event.target.value;
}

html.ts

<form id="formId" #form="ngForm" (submit)="onSubmit(form)">

<!-- Group1 -->
<input type="hidden" name="Id" [(ngModel)]="service.formData1.Id" > 
<input id="Name" name="Name" [(ngModel)]="service.formData1.Name" placeholder='Tagno'>
<input type="radio" name='Score' value='1' [(ngModel)]="service.formData1.Score" (change)="onRadio1('5')"> &nbsp;
<input id="Remark" name="Remark" [(ngModel)]="selectedValue1" [(ngModel)]="service.formData1.Remark">
<br><br>

  
<div>
    <div style="display: inline-block;" id="toast_target">
        <button type="submit" >Save</button>
    </div>
</div>
</form>    

Expected output

Name Score Remark
Horse 1 5
Cow
Cat 2 5

Solution

  • There can be only one [(ngModel)] I think that is why you are getting bugs.

    Whatever actions you want to do, just update on a single property.

    <input id="Remark" name="Remark" [(ngModel)]="service.formData1.Remark">
    

    So the event, should update the service.formData1.Remark property.

    onRadio1(event: any): void {
     this.service.formData1.Remark = event.target.value;
    }