Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while adding "for" attribute to label in angular 2.0 template

Tags:

I use the Angular 2.0 framework and try to create an input component. Also I use Google MDL and it's HTML structure required to have labels to input. Angular gives me an exception:

EXCEPTION: Template parse errors:
Can't bind to 'for' since it isn't a known native property ("s="mdl-textfield__input" type="text" id="{{input_id}}">
        <label class="mdl-textfield__label" [ERROR ->]for="{{input_id}}">{{input_label}}</label>
    </div>"): InputUsernameComponent@2:44

Here is the code:

import {Component} from 'angular2/core';
import {Input} from 'angular2/core';

@Component({
    selector: 'input-username',
    template: `<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="{{input_id}}">
        <label class="mdl-textfield__label" for="{{input_id}}">{{input_label}}</label>
    </div>`
})

export class InputUsernameComponent {
    @Input('input-id') input_id: string;
    @Input('input-label') input_label: string;
}

How can I resolve this issue?

like image 358
Nikita Nikitin Avatar asked Jan 10 '16 11:01

Nikita Nikitin


1 Answers

update

In recent Angular2 versions for should be mapped to htmlFor automatically to avoid this kind of problem.

original

You need attribute binding instead of proper binding

<label class="mdl-textfield__label" attr.for="{{input_id}}">{{input_label}}</label>

or

 <label class="mdl-textfield__label" [attr.for]="input_id">{{input_label}}</label>

or

<label class="mdl-textfield__label" htmlFor="{{input_id}}">{{input_label}}</label>

htmlFor is the property that reflects the for attribute (https://developer.mozilla.org/de/docs/Web/API/HTMLLabelElement)

See also HTML - attributes vs properties

like image 79
Günter Zöchbauer Avatar answered Oct 12 '22 00:10

Günter Zöchbauer