0

The problem I'm facing is setting ngModel's variable name using a variable. To elaborate:

The json being used here as 'options' is:

{
  "a": [
    "a1",
    "a2",
    "a3"
  ],
  "b": [
    "b1",
    "b2",
    "b3",
    "b4"
  ],
  "c": [
    "c1",
    "c2",
    "c3",
    "c4",
    "c5",
    "c6"
  ]
}.

The array 'keys' consists of {"a", "b", "c"} and has been created in the component class using -
this.keys = Object.keys(this.options);

What I'm doing here is creating different tabs on the html page for each key, with their values as radio buttons i.e. tabs are "a", "b" and "c" and each tab has corresponding values from options ("a1, a2, a3" on tab a, "b1, b2, b3 and b4" on tab b and so on) as radio buttons. It's working this far.

The problem pops up while trying to set the variable as the value of the key ("a", "b" and "c") and returning the corresponding selected radio button as the value for each tab. To clarify, I want to return a = a1 or a2 or a3 , b = b1 or b2 or b3 or b4 and c= c1 or c2 or c3 or c4 or c5 or c6 (based on my selection). I'm not able to set ngModel to any relevant variable to achieve this. I'm able to set ngModel to "a", "b" or "c" directly, but not using loop variables such as key or access keys using an index. Also, in case it is relevant, I'm using formGroup for this form.

Any help would be appreciated. I'm not sure if i've explained this well enough, so please feel free to ask questions. ( And I'm pretty new to Angular so I may have missed something obvious, though I've been trying to solve this for a while :/ )

<div *ngFor="let key of keys">
<md-tab label="{{key}}">

  <fieldset class="fieldset">

    <legend>{{key}}</legend>

    <div class="row">

          <div *ngFor="let opt of options[key]" class="large-3 small-6 columns end">
          <input id="{{opt}}" type="radio" formControlName="{{key}}" value="{{opt}}" [(ngModel)]="key.selected" /> 
          <label for="{{opt}}"><span class="{{opt}}"></span>{{opt}}</label><br/>
        </div>
      </div>
  </fieldset>

</md-tab>

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291

1 Answers1

0

it is your starting point:

add in component

public temp = {};

and html

<div *ngFor="let key of keys">
    <legend>{{key}}</legend>
    <div *ngFor="let opt of options[key]">
        <input id="{{opt}}" type="radio" [name]="key" [value]="opt" [(ngModel)]="temp[key]" />
        <label for="{{opt}}"><span class="{{opt}}"></span>{{opt}}<br/></label>
    </div>
</div>
dimson d
  • 1,488
  • 1
  • 13
  • 14
  • I had something similar in my component model: any ={}; whose values I was setting using: formControlName="p_weight" [(ngModel)]="model.p_weight" But was having trouble with the variable (as "model.key" or using interpolation). Using it as an index as you mentioned worked! Thanks a lot!! – apeksha darbari May 01 '17 at 20:45