Reputation: 39
I have created some elements:
<span *ngFor="let versuch of versuche">
<div id="titleId[versuch]"><br></div>
</span>
titleId
is a list of strings, where my element-ids are stored).
But if I try to get access to the elements, with document.getElementById('__title__5')
, the element is not found (__title__5 is one of the element id's).
So do you know a way to set the id's per code?
Upvotes: 1
Views: 1996
Reputation: 1316
ngAttr
for binding to arbitrary attributes AngularJS
For example, considering this template
<span *ngFor="let versuch of versuche">
<div ng-attr-id="{{ 'titleId-' + versuch }}"><br></div>
</span>
Doc - https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes
Angular
<li *ngFor="item of items" #elem [attr.id]="item.id">
{{ item.name}} ID: {{elem.id}}
</li>
Upvotes: 0
Reputation: 31105
Use index
from the *ngFor
. Try the following
Option 1 - titleId
is an array of strings
<span *ngFor="let versuch of versuche; let i=index">
<div attr.id="{{titleId[i]}}"><br></div>
</span>
Option 2 - titleId
not used
If you need to have corresponding id's based on the index of the versuche
variable, you can skip the variable titleId
and do it directly in the template.
<span *ngFor="let versuch of versuche; let i=index">
<div [attr.id]="'__title__' + i">{{versuch}}<br></div>
</span>
Option 3 - titleId
is an object
If the titleId
is an object with keys corresponding to each versuche
, then the following should work
component
versuche = [ 'versuche_1', 'versuche_2', 'versuche_3' ];
titleIdObj = {
'versuche_1': '__title__1',
'versuche_2': '__title__2',
'versuche_3': '__title__3',
}
template
<span *ngFor="let versuch of versuche">
<div attr.id="{{titleIdObj[versuch]}}">{{versuch}}<br></div>
</span>
Working example: Stackblitz
Upvotes: 0
Reputation: 41
Use [id] instead of id as in the example below:
<span *ngFor="let versuch of versuche">
<div [id]="titleId[versuch]"><br></div>
</span>
Upvotes: 1