Issue
Below is my code where I need to pass a default value to a radio button.
<div class="ui-g-12">
<p-radioButton name="group1" value="Option 1" label="Option 1" [(ngModel)]="val1" inputId="opt1"></p-radioButton>
</div>
<div class="ui-g-12">
<p-radioButton name="group1" value="Option 2" label="Option 2" [(ngModel)]="val1" inputId="opt2"></p-radioButton>
</div>
<div class="ui-g-12">
<p-radioButton name="group1" value="Option 3" label="Option 3" [(ngModel)]="val1" inputId="opt3"></p-radioButton>
</div>
Can anyone please explain how to set the default value to a radio button when the form loads?
Solution
First change the way you build your form to the ReactiveForms
way:
<form [formGroup]="myForm">
<div class="ui-g-12">
<p-radioButton name="group1" value="Option 1" label="Option 1" formControlName="myRadio" inputId="opt1"></p-radioButton>
</div>
<div class="ui-g-12">
<p-radioButton name="group1" value="Option 2" label="Option 2" formControlName="myRadio" inputId="opt2"></p-radioButton>
</div>
<div class="ui-g-12">
<p-radioButton name="group1" value="Option 3" label="Option 3" formControlName="myRadio" inputId="opt3"></p-radioButton>
</div>
</form>
And in the component set the default value when you initialize it:
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 5';
myForm;
constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
myRadio: ['Option 1', []] // This set default value
})
}
}
Runing example: https://stackblitz.com/edit/angular-fu81jc
Primeng docs: https://www.primefaces.org/primeng/#/radiobutton
ReactiveForms docs: https://angular.io/guide/reactive-forms
Answered By - Rubén Soler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.