Dng
Dng

Reputation: 643

Dynamic Radio Buttons 2 Way Binding using ngModel - Angular 6

I'm generating dynamic radio buttons which will all be consolidated on form submit not individually. I however need to bind them to a particular value in my component individually which I have no clue how to do.

I've seen the other related posts on this subject on stackoverflow but none of them seem to help me out.

Here's my code:

<input type="radio" class="one" id="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date}}" name="{{post.id}}" [value]='candidate.user._id' [(ngModel)]="post.id">
<label for="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date }}">
    <span>
        <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/242518/check-icn.svg" alt="Checked Icon" />
    </span>
</label>

Any help will be appreciated.

Upvotes: 0

Views: 5423

Answers (1)

Nasiruddin Saiyed
Nasiruddin Saiyed

Reputation: 1466

Take a new variable of an array in component :

private radioButtonValues : Array<any> = [];

then bind it in you ngModel with index i as :

<input type="radio" class="one" 
       id="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date}}" 
       name="{{post.id}}" 
      [value]='candidate.user._id' 
      [(ngModel)]="radioButtonValues[i]">

if you want some manipulation you can also use ngModelChange event for more functionality.

<input type="radio" class="one" 
       id="{{ i }}_{{ candidate.user._id }}_{{post.id}}_{{ candidate.date}}" 
       name="{{post.id}}" 
       [value]='candidate.user._id' 
       [(ngModel)]="radioButtonValues[i]" 
       (ngModelChange)='changeEventInRadioButton($event)'>

then declare function in your component class

changeEventInRadioButton($event) {
    console.log($event);
}

at last on form submission check

onSubmit(){
    console.log(this.radioButtonValues);
}

Upvotes: 4

Related Questions