Nathan Taylor
Nathan Taylor

Reputation: 25

Angular2: binding to input radio name doesn't work

In Angular2, one-way binding to the name attribute for a group of radio inputs doesn't work. For example:

<div [ngFormModel]="form">
  <input type="radio" [name]="varName" [id]="id1" ngControl="r1">
  <input type="radio" [name]="varName" [id]="id2" ngControl="r2">
  <input type="radio" [name]="varName" [id]="id3" ngControl="r3">
</div>

When loading the page, name is not an attribute on any of those radio inputs.

Upvotes: 1

Views: 515

Answers (2)

N.Schipper
N.Schipper

Reputation: 1668

If this works anything like the binding to the select property the name property will be set on the javascript dom element. Meaning while it does not display within the view it actually has been set on the HTMLElement.

Which is illustrated with the following plunk:

import {Component} from '@angular/core'
import {ControlGroup, Control} from '@angular/common'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
  <form [ngFormModel]="group">
      <input type="radio" [attr.name]="name" ngControl="test">
      <input type="radio" [attr.name]="name" ngControl="test2" ref-example>
      <input type="radio" [name]="name" ngControl="test3" ref-exampletwo>
      <p>using [attr.name]: {{example.name | json }}</p>
      <p>using [name]: {{exampletwo.name | json }}</p>
  </form>
  `
})
export class App {
  name: "test"
  group: ControlGroup

  constructor() {
    this.group = new ControlGroup({
      test: new Control(""),
      test2: new Control(""),
      test3: new Control("")
    })
  }
}

http://plnkr.co/edit/xHkgb0BgPzZLwyFpTo1W?p=preview

What you actually want to do is the following:

[attr.name]="name"

This will set the property on the element.

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657058

I guess what @Schippie wrote was correct. Use

[attr.name]="name"

instead of

[name]="name"

(his Plunker had a few issues)

Plunker example

Upvotes: 2

Related Questions