typescript 将“for”属性添加到 angular 2.0 模板中的标签时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34704671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error while adding "for" attribute to label in angular 2.0 template
提问by Nikita Nikitin
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:
我使用 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
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?
我该如何解决这个问题?
回答by Günter Z?chbauer
update
更新
In recent Angular2 versions for
should be mapped to htmlFor
automatically to avoid this kind of problem.
在最近的 Angular2 版本中for
应该htmlFor
自动映射到避免这种问题。
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)
htmlFor
是反映for
属性的属性(https://developer.mozilla.org/de/docs/Web/API/HTMLLabelElement)
See also HTML - attributes vs properties
另请参阅HTML - 属性与属性