Issue
I have created a checklist of questions with radio buttons as an Angular dialog. Once the questions have been answered (i.e. radio buttons checked), I want this choice to be remembered even if the dialog is closed and then reopened. I am not managing to have the correct radio buttons checked when I open the dialog.
The information is available, the first div contains false
, the second div contains true
as expected.
<div>{{ form.get('riskGroupPoster')?.value}}</div>
<div>{{ form.get('riskGroupPoster')?.value === false }}</div>
This is my button template:
<div class="radio-group">
<zh-radio [smallRadio]="true" >
<input type="radio" name="riskGroupPoster" formControlName="riskGroupPoster" value="true" [checked]="form.get('riskGroupPoster')?.value === true"/>
<label >ja</label>
</zh-radio>
<zh-radio [smallRadio]="true">
<input type="radio" name="riskGroupPoster" formControlName="riskGroupPoster" value="false" [checked]="form.get('riskGroupPoster')?.value === false"/>
<label>nein</label>
</zh-radio>
</div>
I would expect the second button (with the label "nein") to be checked, but it's not.
I thought the problem might be with how I'm binding the value
property based on this question, but if I change the attribute to [value]="true"
and [value]="false"
respectively (adding square brackets), the value of 'riskGroupPoster'
is "on"
regardless of which of the two radio buttons I click. Same thing when I use [value]=true
(without the quotation marks).
Now I think there's something wrong with the checked
attribute: If I set [checked]="true"
for one of the buttons it is still not checked when I open the dialog.
What am I doing wrong?
Solution
Turns out with Angular reactive forms I don't need the [checked]
property, just setting the value of a FormControl will automatically check the radio button. The problem was a mix-up with the data types. I defined the FormControl as having a type of string or null:
riskGroupPoster: FormControl<string | null>;
This aligns with how I set the value in the template, where it is also a string:
<input type="radio" name="riskGroupPoster" formControlName="riskGroupPoster" value="true"/>
However on opening the dialog the data I pass in was of type boolean (not string), which caused the whole thing to silently fail. Casting the received value to string before assigning it to the FormControl fixed the problem and checked the correct radio button:
control.setValue(this.oldChecklist['riskGroupPoster']?.toString() || null);
Answered By - Ada
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.