5

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?

Mike Schenk
  • 1,512
  • 9
  • 21

1 Answers1

0

One way is to use the @Input decorator and pass values from parent where you have the component to the child component where your form or lable is

parentcomponent

<myComponent idToUse="id1"></myComponent>
<myComponent idToUse="id2"></myComponent>

ChildComponent

@Component({
selector : "myComponent",
template: `<div>
    <label for="{{idToUse}}">Name</label>
    <input [(ngModel)]="name" type="text" id="{{idToUse}}"/>
</div>`
})
export class childComponent {
@Input() idToUse;
}

You can find a similar example for using same compnent multiple times in this link Angular2 .. Using the same component to show different data on the same page depending on service response

praveen
  • 489
  • 6
  • 12