Is there anyway to easily bind custom string to id and for in html element using Angular2?

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?

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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

Jason
Guest

The correct way to bind attribute value:

[attr.id]="value"