I have a form using a template driven form and I whant to make a radio button selected by default but it doesnt work, this is a part of my code:
<div class="donut-form-promos">
<span>Promo:</span>
<div class="donut-form-promos-choices">
<input
type="radio"
name="promo"
[value]="'newPromo'"
rquired
ngModel
#promo="ngModel"
/><span>New</span>
<input
type="radio"
name="promo"
[value]="'limitedPromo'"
required
ngModel
#promo="ngModel"
/><span>Limited</span>
<input
type="radio"
name="promo"
[value]="'clubPromo'"
required
ngModel
#promo="ngModel"
/><span>Club memeber</span>
<input
type="radio"
name="promo"
[value]="undefined"
required
ngModel
#promo="ngModel"
[checked]="'checked'"
/><span>None</span>
</div>
</div>
I upload the example in stakeblitz too , this is a link: https://stackblitz.com/edit/angular-ivy-dd8u6v?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts
Thank you.
Angular will treat all the radio button elements with same name attribute as a common control. So you can say that a bunch of radio button elements with same name is entirely a single control system input with one single value as output (similar to select with multiple options). This value decided by the value of the selected radio button element. But in angular, it's opposite is also true i.e., the value of the control will decide which of it's radio button is selected. So for example, if a radio button A has value "1" and radio button B has value 2, and they are part of same control i.e, have same name, you can set the value of the control as "2" during initialization of the component and it will reflect on it's radio buttons, so the radio button B with value "2" will automatically get selected.
Bind the directive ngModel to a default value in the radio button element so that it will automatically be selected in case the default value is equal to it's value such as:
Your Component ts example becomes:
And your template: