user5711656
user5711656

Reputation: 3678

How to print selected value of radio button?

Can you please tell me how to print selected value of radio button ? I tried like this but it not work? https://stackblitz.com/edit/angular-grtvc7?file=src%2Fapp%2Fapp.component.ts

<mat-radio-group [(ngModel)]="favoriteName">
  <mat-radio-button  *ngFor="let name of names" [value]="name">
    {{name}}
  </mat-radio-button>
</mat-radio-group>

<div class="example-selected-value">Your favorite season is: {{favoriteName}}</div>

this example not work for me ..

Can you suggest another ay to do this ? because I don't want to use [(ngModel)] ? But first why it is not working using ngmodel

Upvotes: 0

Views: 487

Answers (3)

Sujan Gainju
Sujan Gainju

Reputation: 4769

You have forgot to give a name attribute to mat-radio-group

<mat-radio-group [(ngModel)]="favoriteName" name="fav">
  <mat-radio-button  *ngFor="let name of names" [value]="name">
    {{name}}
  </mat-radio-button>
</mat-radio-group>

<div class="example-selected-value">Your favorite season is: {{favoriteName}}</div>
</form>

Demo

Upvotes: 0

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

If you are using form tagyou must name yor form elements as @Sachila Ranawaka said or you can add ngModelOptions like

<mat-radio-group [(ngModel)]="favoriteName"  [ngModelOptions]="{standalone: true}">
  <mat-radio-button  *ngFor="let name of names" [value]="name">
    {{name}}
  </mat-radio-button>
</mat-radio-group>

<div class="example-selected-value">Your favorite season is: {{favoriteName}} </div>
</form>

if you check there is an error in you console exmplane all of this

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41427

Since you are using form tag You need to name tag for form elements

<mat-radio-group [(ngModel)]="favoriteName" name="something">

Demo

Upvotes: 1

Related Questions