Reputation: 2357
Please see this code snippet from the docs:
When using radio buttons in a reactive form, ...
import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form">
<input type="radio" formControlName="food" value="beef" > Beef
<input type="radio" formControlName="food" value="lamb"> Lamb
<input type="radio" formControlName="food" value="fish"> Fish
</form>
<p>Form value: {{ form.value | json }}</p> <!-- {food: 'lamb' } -->
`,
})
export class ReactiveRadioButtonComp {
form = new FormGroup({
food: new FormControl('lamb'),
});
}
My question: What should I do to make one of those radio buttons checked by default? Do I need to add some additional property to the FormControl? Or should I modify something in the template?
(I tried adding a checked
attribute to one of them in the template, but for some reason it doesn't do anything. I looked at it in the browser using "Inspect element", and the attribute is there in the DOM, yet it has no effect on the state of the radio button. It doesn't become checked.)
Upvotes: 2
Views: 4613
Reputation: 9260
I believe the only problem you have is that you're not using ReactiveFormsModule
. With your current setup you have already selected lamb
and it shows selected when using ReactiveFormsModule
.
In your module you'll want to import this:
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ BrowserModule, ReactiveFormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
Here is a working plunker.
Upvotes: 3
Reputation: 1115
For every option there is a selected attribute you can set if you want that option as default. you can write:
<option selected></option>
or:
<option selected="selected"></option>
and change that value for example in javascript with the YourOptionTag.selected method.
hope it helps
Upvotes: 1