【问题标题】:Error while adding "for" attribute to label in angular 2.0 template在 Angular 2.0 模板中将“for”属性添加到标签时出错
【发布时间】:2016-04-14 18:23:50
【问题描述】:

我使用 Angular 2.0 框架并尝试创建一个输入组件。 我也使用 Google MDL,它的 HTML 结构需要输入标签。 Angular 给了我一个例外:

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

代码如下:

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;
}

我该如何解决这个问题?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    更新

    在最近的 Angular2 版本中,for 应该自动映射到 htmlFor 以避免此类问题。

    原创

    你需要属性绑定而不是正确的绑定

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

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

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

    htmlFor 是反映for 属性的属性 (https://developer.mozilla.org/de/docs/Web/API/HTMLLabelElement)

    另见HTML - attributes vs properties

    【讨论】:

    • @Günter : 在 RC5 中这不起作用,现在是坏了还是有新的方法可以做到这一点?
    • 绑定到for 现在应该可以工作了。 AFAIK 他们添加了一些映射。怎么破?旧方法应该仍然有效。
    • 没有绑定到 for 仍然被破坏但是当我使用你的任何方法时它不会给我错误它只是不起作用。当我在标签中添加 for 时,我期望当我单击标签时,输入会聚焦。但是,当我单击它时,什么也没有发生
    • 这里是问题的链接:stackoverflow.com/questions/39163205/…
    • @deadManN 这就是第一行所说的(“更新”)。在旧版本中,这不起作用。
    猜你喜欢
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2022-09-24
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多