I understand how to use ElementRef and that one should avoid setting element ids, but there are still situations where you want to set an element's id attribute.
For example, with inputs and labels (cannot nest because of 3rd party CSS):
<input [attr.id]="'myinput'+instanceId" />
<label = [attr.for]="'myinput'+instanceId">My Label</label>
I've just been incrementing a number like this for simplicity:
let numInstances = 0;
@Component({
})
export class MyComponent {
private instanceId: number;
constructor(){
this.instanceId = numInstances++;
}
}
But I was wondering if there is a Component Instance namespace I can use in templates instead. Something like this? Angular2 would replace # with unique string for component instance.
<input [attr.id]="#myinput" />
<label = [attr.for]="#myinput">My Label</label>
If this doesn't exist, do you think I should make a feature request to the Angular2 team?
After reading some discussions online I decided to use lodash method proposed in https://github.com/angular/angular/issues/5145#issuecomment-256354115
It works for me, hope it helps someone else!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With