Home > front end >  Set selected Radio Button from group using Typescript
Set selected Radio Button from group using Typescript

Time:11-13

Have this on the html side:

 <input type="text" id="title" class="form-control" formControlName="title" maxlength="50"/>
 <div >
 <input type="radio"  value="2" name="rgLongTerm"> <label> all </label>
 <input type="radio"  value="0" name="rgLongTerm"> <label> no </label>
 <input type="radio"  value="1" name="rgLongTerm"> <label> yes </label>
 </div>

And I have the textbox with value set like this on the .ts side:

 form.controls.title.patchValue(filter.data);

(and that part works) where filter.data comes from the database

Now, I added this radio button group, and just like the textbox is getting filled with the patchvalue, I would like to select the one of 3 radio buttons, based on the value which is inside a filter.data2 (can have value 0,1,2) for example.

How can I do that?

CodePudding user response:

The value in your input should be [value]=0 if your filter.data2 is a number. You’re also missing the formControlName in the input. An example should be like this: <input type="radio" formControlName=“rgLongTerm” [value]=2 name="rgLongTerm"> <label> all </label>

Have you tried form.controls.rgLongTerm.patchValue(filter.data);? Also you can also set a default value by doing this

this.form = new FormGroup({
   'rgLongTerm': new FormControl(filter.data2)
});
  • Related