koque
koque

Reputation: 2256

Angular 2: Can't get formGroup to work with Radio Button

I need to pass the rating value from my template to my component. I am currently passing it as a parameter to a method in the component like so:

<form [formGroup]="ratingForm">
                <div *ngFor="let rating of ratings" class="radio">
                    <input type="radio" name="rating" value="rating.value" 
                        (change)="filterByRating(rating.value)">                        
                        {{rating.title}}
                    <br>
                </div>
            </form>

Component:

 filterByRating(rating) {

}

This works but I would rather not pass the value as a parameter. I tried using [formControl] and formControlName without success. The examples I have found are using hardcoded values but that doesn't work for me. Any ideas?

Upvotes: 0

Views: 126

Answers (1)

Mani S
Mani S

Reputation: 2561

This might be helpful for you. You should use formControlName from @angular/forms with formGroup in your view.

<form [formGroup]="ratingForm">    
 <div class="radio" *ngFor="let rating of ratings">
      <label>
        <input
          type="radio"
          formControlName="rating"
          [value]="rating.value">{{ rating.title }}
      </label>
 </div>
</form>

In your component:

ngOnInit() {
   this.ratingForm = new FormGroup({
     'rating': new FormControl('ratingName')
      .... something like this

   });
}

// This gives you the value of the rating selected from view
console.log(this.ratingForm.value.rating);

Upvotes: 1

Related Questions