2

Consider the following plunker

import {Component} from 'angular2/core'

@Component({
  selector: 'my-app',
  template: `
    <div *ngFor="#option of myHashMap">
        <input type="radio" name="myRadio" id="{{generateId(option['id'])}}">
        <label for="{{generateId(option['id'])}}">
            {{option['name']}}
        </label>
    </div>        
    `
})
export class App {

    myHashMap = [{'name': 'myName1', 'id': 'id1'},{'name': 'myName2', 'id': 'id2'}]

    generateId(key) {
      return "myKey" + key;
    }
}

I am trying to bind a string to id in input and the same string to for in label. However I run into

Can't bind to 'for' since it isn't a known native property ("hMap">
    <input type="radio" name="myRadio" id="

Is there an angular2 idiomatic way of achieving this?

testing
  • 2,303
  • 4
  • 20
  • 32

2 Answers2

2

id can be bound to using one of

id="{{someProp}}"
[id]="someProp"

because id is a property on every element.

For for you need to use one of

[attr.for]="someProp"
attr.for="{{someProp}}"
[htmlFor]="someProp"
htmlFor="{{someProp}}"

because htmlFor is the property that is reflected to the for attribute.

See also Properties and Attributes in HTML

Plunker example

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Why should it not work? Elements have an `id` property and binding works just fine (see Plunker link) – Günter Zöchbauer Oct 11 '16 at 17:13
  • Hmm, I guess it still does work, but I remember having problems with my code when I did not use **[attr.id]**. In the generated HTML, there is also *ng-reflect-id="someId"* when you use **[id]**, but this attribute does not exist when you use **[attr.id]**. Though I'm not sure what ng-reflect is for. – Arlo Oct 11 '16 at 17:26
  • `ng-reflect-id` is created for property-bindings and `[id]` is a property binding. Perhaps you tried binding to an `@Input() id;` which doesn't work while `[attr.id]=".."` might work (not tried myself). – Günter Zöchbauer Oct 11 '16 at 17:29
  • https://angular.io/docs/ts/latest/guide/template-syntax.html does say "Attribute (the exception)". So maybe you're right that the property form should be preferred. I could swear it didn't work for me once, but it does now. Maybe there was a change in one of the betas/RCs I was using? – Arlo Oct 11 '16 at 17:53
1

The correct way to bind attribute value:

[attr.id]="value"
kemsky
  • 14,727
  • 3
  • 32
  • 51
  • This would not work with `for` though. `[attr.for]` will give error – testing Apr 18 '16 at 02:21
  • I was wrong about `[attr.for]`, it works, I was just using it incorrectly `[attr.for]={{myVariable}}` will not work I need `[attr.for]="myVariable"` – testing Apr 18 '16 at 06:00