How do I get the id of a form input element for a label in a reusable Angular component...

Discussão em 'Angular' iniciado por Mike Schenk, Janeiro 15, 2025.

  1. Mike Schenk

    Mike Schenk Guest

    I have an Angular 2 component that holds some form input elements and labels that should be associated with them. Multiple instances of the component might be in the page at once. How do I set the for attribute of the label and the id attribute of the input to connect them to each other?

    If I hard-code the id of the input element in the template then it won't be unique on the page. But I don't want to have to pass an identifier into this component from its containing component; the connection between the label and form element is just this component's concern.

    <div>
    <label for="???">Name</label>
    <input [(ngModel)]="name" type="text" id="???"/>
    </div>


    AngularJS had a scope $id property that could be used to build a unique id. Does Angular have anything similar for components?

    Continue reading...

Compartilhe esta Página