regina
regina

Reputation: 511

How to fetch radio button value dynamically in angular 2?

Need to display radio button values dynamically from array, and fetch the value of it based on which I need to display a <div>. please find the code below

html

<div *ngFor = "let fruit of fruits"
<input type = "radio"/>{{fruit}}>
</div>

component.ts -> contains the following array

fruits : string[] = ["apple", "mango"];

With this I am getting the radio buttons apple and mango.Need to get the value of the selected radio button (in assigning[(ngModel)], value) and Need to display another div based on individual selections. Please guide me on this

Upvotes: 1

Views: 2027

Answers (2)

Akhilesh Kumar
Akhilesh Kumar

Reputation: 55

<div *ngFor="let fruit of fruits">
<input type="radio" [value]="fruit" 
(change)="selectedFruitValue(fruit)">
{{fruit}}
</div>

in your ts file
first define a variable
i.e
fruitValue:string

and then write a function

selectedFruitValue(fruit){

this.fruitValue = fruit;

//for checking purpose
 console.log('fruit value is':+this.fruitValue);

}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

You can use [value]

<div *ngFor="let fruit of fruits">
    <input type="radio" formControlName="options" [value]="fruit">
    {{fruit}}
</div>`

Upvotes: 2

Related Questions