0
votes

I am using Angular 6 and Angular Angular Material, I have dynamic list of polls with list of options. I want to show selected option with two way data binding. as my list is dynamic i want to pass variable in [(ngModel)]. tried passing variable but no luck please suggest alternate solution stackblitz example code

1
You're using the same variable (mySelection) for both questions. What did you expect to happen? - Lazar Ljubenović

1 Answers

1
votes

You were using the same variable (mySelection) for both questions. Instead, you need to use two different variables, or even better, an array. Here's the fixed version on StackBlitz and here's the relevant code.

Template

<ol>
    <li *ngFor="let poll of polls;let i = index">
        {{poll.name}}

        <mat-radio-group class="example-radio-group" [(ngModel)]="selectedAnswers[i]">
            <mat-radio-button class="example-radio-button" *ngFor="let option of poll.options" [value]="option.answer">
                {{option.answer}}
            </mat-radio-button>
        </mat-radio-group>
    <strong>Seleted Answer : {{selectedAnswers[i]}}</strong>
    <button  [disabled]="selectedAnswers[i]==undefined" mat-raised-button color="accent">save</button>
  </li>
</ol>

<pre>{{ selectedAnswers | json }}</pre>

Component

@Component({
  /* ... */
})
export class AppComponent  {

  selectedAnswers = []

  polls = [
    /* ... */
  ]
}