1

I have a dynamic form where I want to make a radio control. The controls value for each choice should be an array. This works but it doesnt seem to be initializing the selected choice when the page loads.

Here is an example of what I want to happen (the value is set to an integer so it works). Notice how "four" is selected by default.

Here is an example of what happens (value is set to an array and doesnt select the default value). Notice how nothing is selected by default.

If there a way to fix this? I need the form to return the array on submit.

1 Answer 1

2

New answer:

https://stackblitz.com/edit/mat-radio-group-with-object-as-value

I created an object that extends FormControl and sets the value based on a given list of choice objects.


Old answer:

Ok so after some fiddling.... I realized the problem seems to be that material radio button is comparing the memory locations of the objects for the choices and the formcontrol value, instead of comparing the actual values of the array. If you know java they are doing if(OBJECT_A == OBJECT_B) instead of if(OBJECT_A.equals(OBJECT_B)). I figured this out by making a loop do the comparison and use the value from the choice list instead and it works.

However, it isnt the best solution and actually stopped working in some cases in my implementation. I have since found a better way of doing it. Here is the fully working example. I use the 'checked' attribute of the radio button with a compare function that performs a proper value compare. This worked, but still had one other issue... When I reset the form, if the value of the radio button was on the default choice, the reset method would clear the checked button. So I had to add an if condition in the reset method to make sure the value of the control was not already equal to the default choice, before resetting the value.

For anyone else running into this issue. The select control already has a compareWith attribute that allows you to get around all of this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.