重复的"id"Angular 2组件中的属性 [英] Duplicate "id" attribute in Angular 2 component
问题描述
上下文
我正在为复选框编写自定义Angular组件.该组件将呈现一个复选框标签和一个标签标签.复选框的"id"属性和标签的"for"属性都设置为组件的 id
属性(组件的 @Input
),以确保单击标签将切换复选框.模板的简化版本如下:
I'm writing a custom Angular component for a checkbox. The component renders a checkbox tag along with a label tag. The "id" attribute of the checkbox and the "for" attribute of the label are both set to the component's id
property (an @Input
to the component) to ensure that clicking the label will toggle the checkbox. A simplified version of the template looks like:
<div class="checkbox">
<input type="checkbox" [id]="id" />
<label [for]="id"><ng-content></ng-content></label>
</div>
问题
当我在组件上设置"id"属性(例如< my-checkbox id ="hello">检查我</my-checkbox>
)时,会出现一个"id"属性是在DOM中的组件包装标签上自动设置的.这会导致DOM中的ID重复,因为我已经在组件内部的复选框上设置了"id"属性.这是无效的,并且会破坏浏览器的默认通过单击标签切换"行为.DOM输出为:
When I set an "id" prop on my component (e.g. <my-checkbox id="hello">Check me</my-checkbox>
), an "id" attribute is automatically set on the component wrapper tag in the DOM. This results in duplicate ids in the DOM because I'm already setting an "id" attribute on the checkbox inside the component. This is invalid and breaks the browser's default toggle-by-clicking-the-label behavior. The DOM output is:
<my-checkbox id="my-checkbox" ng-reflect-id="my-checkbox" ng-reflect-checked="true">
<div ng-reflect-ng-class="[object Object]" class="checkbox">
<input class="checkbox__element" type="checkbox" name="fire_missiles" ng-reflect-id="my-checkbox" id="my-checkbox" value="fire_missiles" ng-reflect-checked="true">
<label class="checkbox__label" ng-reflect-html-for="my-checkbox" for="my-checkbox">
Fire missiles?
</label>
</div>
</my-checkbox>
是否有办法a)删除垃圾容器标签或b)停止将"id"属性作为属性自动反射到容器上?
Is there a way to either a) get rid of the garbage container tag or b) stop the automatic reflection of the "id" prop onto the container as an attribute?
注意:使用应用于div之类的属性选择器无济于事,它只是将多余的"id"从< my-checkbox/>
移至div.
NOTE: Using an attribute selector applied to something like a div doesn't help, it just moves the extra "id" from <my-checkbox />
to the div.
推荐答案
我只需重命名复选框的ID(并因此重命名标签的 for
属性),以免与组件的ID冲突.,就像这样:
I would simply rename the checkbox's id (and hence the label's for
attribute) so that it doesn't clash with the component's id, like so:
<input id="{{ id }}-checkbox" …>
<label for="{{ id }}-checkbox">…</label>
这篇关于重复的"id"Angular 2组件中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!