Duplicate id attribute in Angular 2 component

Context

I am writing a special Angular component for a checkbox. The component displays a flag tag along with a tag tag. The "id" attribute of the flag and the "for" attribute of the label are set to the component property id(a @Inputfor the component) to make sure that clicking on the label will switch this flag. A simplified version of the template looks like this:

<div class="checkbox">
    <input type="checkbox" [id]="id" />
    <label [for]="id"><ng-content></ng-content></label>
</div>

Problem

When I install the "id" support on my component (for example <my-checkbox id="hello">Check me</my-checkbox>), the "id" attribute is automatically set in the component wrapper tag in the DOM. This leads to duplicate identifiers in the DOM, as I already set the id attribute in the checkbox inside the component. This is invalid and violates the default behavior of the browser. DOM Output:

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

Is there a way to either: a) get rid of the garbage container tag, or b) stop automatically reflecting the id support on the container as an attribute?

NOTE. Using an attribute selector applied to something like a div doesn't help, it just moves the extra "id" out of <my-checkbox />the div.

Thank!

+4
source share
3

Elliot, :

checkbox (, , for), , :

<input id="{{ id }}-checkbox" …>
<label for="{{ id }}-checkbox"></label>
+3

, :

constructor(elementRef: ElementRef) {
    elementRef.nativeElement.removeAttribute("id");
}

id <my-checkbox></my-checkbox>

0

You can pass idas expression:

<my-checkbox [id]="'hello'">Check me</my-checkbox>

In this case, the component tag does not contain an attribute idin the DOM, it contains only an attribute ng-reflect-idthat does not affect the default behavior for the label.

0
source

Source: https://habr.com/ru/post/1665937/


All Articles