I need to get value from radio button in angular. Suppose to have this html code:
<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="dog" name="gob" value="i" [checked]="true" (change)="onItemChange(item)"/>Dog
</label>
<label class="radio-inline">
<input class="form-check-input" type="radio" [(ngModel)]="cat" name="cat" value="p" (change)="onItemChange(item)"/>Cat
</label>
In my ts page I need to get the value of radio button like
dog.value
My purpose is:
- Set default cheched to first radio button
- Get the value when I click on radio button
Anyone can help me?
You can bind the data of radio button. Just add the value for radio button and change in the ngModel
html
<input class="form-check-input" type="radio" value="dog"
[(ngModel)]="dog.value" name="gob" value="i" [checked]="true"
(change)="onItemChange($event)"/>
ts
onItemChange(value){
console.log(" Value is : ", value );
}
The data binding of radiobuttons is dependent of the value attribute. So if you set your variable dog equels the string "dog" the first radiobutton will be selected.
To get the value of the radiobutton on click you can either pass the string directly in your onItemChange event or access it via the event variable:
https://stackblitz.com/edit/angular-csusjt?file=src%2Fapp%2Fapp.component.html
来源:https://stackoverflow.com/questions/52927608/how-get-checked-value-from-radio-button-angular