-2

I have a question about how I can implement radio buttons in my form with ngControl

Here is the code of the template:

<div class="form-group">
    <label class="radio-inline" *ngFor="#size of formModel.sizes">
        <input type="radio" ngControl="ourSize" #ourSize="ngForm" value="{{ size }}" >
        {{ size }}
    </label>
</div>

here is the code of model:

this.formModel = {
        sizes: ['asd1', 'asd2', 'asd3']
}

I have such an error: enter image description here

P.S. I have already checked another answer Angular2 - Radio Button Binding but it didn't help me(

Community
  • 1
  • 1
weratius
  • 113
  • 1
  • 12

1 Answers1

3

You need to use radio inputs this way:

@Component({
  selector: 'my-app', 
  template: `
    <form>
      <div class="form-group">
        <label class="radio-inline" *ngFor="#size of formModel.sizes; #i=index">
        <input type="radio" [(ngModel)]="formModel.sizes[i]" #ctrl="ngForm" ngControl="sizeCtrl" name="size"/>
        {{ size.value }}
      </label>
    </div>
    Test: {{ctrl?.value}}
    Values: {{formModel | json}}
  </form>
`
})
export class AppComponent {
  constructor() {
    this.formModel = {
      sizes: [
        new RadioButtonState(true, 'asd1'),
        new RadioButtonState(false, 'asd2'),
        new RadioButtonState(false, 'asd3')
      ]
    };
  }
}

The radio button states are updated according what is selected. It doesn't seem that controls can be used at this level...

Se this plunkr: https://plnkr.co/edit/kHJyq3N5ZtoNyAPz6Kbc?p=preview

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360