Solution 1 :

Use [id] instead of id as in the example below:

<span *ngFor="let versuch of versuche">
    <div [id]="titleId[versuch]"><br></div>
</span>

Solution 2 :

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

Solution 3 :

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>

Problem :

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?

Comments

Comment posted by Michael Beeson

In Angular you can simply use square brackets like so:

Comment posted by angular.io/api/core/ViewChildren#viewchildren

The “Angular way” is use ViewChildren, see

Comment posted by Eliseo

NOT use as name of variable

By