Reputation: 861
Am having simple form using reactive, I can choose option using template driven forms, but I cannot do the same using reactive forms. what am doing wrong here
<form [formGroup]="reactiveform">
<mat-form-field>
<mat-select placeholder="Gender" [(value)]="gendervalue" formControlName="gender">
<mat-option value="female">Female</mat-option>
<mat-option value="male">Male</mat-option>
</mat-select>
</mat-form-field>
</form>
<p>Form value: {{ reactiveform.value | json }}</p>
Upvotes: 1
Views: 8480
Reputation: 701
Also you can set default select value when you creating form with FormGroup, if you don't need a FormBuilder.
For example set default value for gender:
const genders = ['female','male']
this.reactiveform = new FormGroup({
gender: new FormControl(genders[0])
});
patchValue() or setValue() - also good solutions if you want to set select value later after form creation.
Upvotes: 0
Reputation: 748
Using a form group you should not set values through the inputs and outputs in the template. Instead you should do all manipulation of the form's data model using the FormGroup object in the typescript file. If you built your form group using the FormBuilder, you might set the default value like this:
import {FormBuilder} from '@angular/forms';
constructor(private fb: FormBuilder, ...) {
...
}
ngOnInit() {
this.reactiveForm = this.fb.group({
...
gender: myDefaultGender,
...
});
}
You may then update the value by .patchValue()
this.reactiveForm.patchValue({ 'gender': myNewGender });
The parameter map may contain more than only one control's value. If you want to set all values at once you may also use the .setValue() method.
Upvotes: 5
Reputation: 3
In ts file take one variable 'gendervalue' and assign default value to it as male or female whatever you want like In ts file
gendervalue = 'male';
In HTML file Form value: {{ gendervalue }}
check this page for more reference.
Upvotes: 0