Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Component instance namespace/id that can be used in templates

Tags:

angular

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?

like image 360
Arlo Avatar asked Oct 11 '16 17:10

Arlo


1 Answers

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!

like image 131
Darko Avatar answered Sep 28 '22 15:09

Darko