Home > Blockchain >  Is it possible to assign the hash(#) automatically in angular?
Is it possible to assign the hash(#) automatically in angular?

Time:01-31

Is there any way where I can assign the hash(#) automatically to the elements inside an ngfor?

<div *ngFor="let note of notes; index as i">
      <h3 #[note][i]>
        {{ note }}
      </h3>
</div>

The result I would expect would be something like this:

<div>
      <h3 #note11>
        note1
      </h3>
</div>
<div>
      <h3 #note122>
        note12
      </h3>
</div>
<div>
      <h3 #note153>
        note15
      </h3>
</div>

CodePudding user response:

You can use the index variable to automatically assign a unique id to each element in the ngFor loop. Here's an example:

  <div *ngFor="let note of notes; index as i">
      <h3 id="note{{i}}">
        {{ note }}
      </h3>
</div>

This will give each element an id of "note0", "note1", "note2", etc.

Regarding using #, it is not possible to use it in such a way. The # symbol is used to create a template reference variable, you can use it like <h3 #myNote>{{ note }} and you can access the element using myNote in your component.

CodePudding user response:

try this;
<div *ngFor="let note of notes; index as i">
  <h3 #{{note}}{{i}}>
    {{ note }}
  </h3>
</div>

Note: 
   This would do your work but # is used to create template reference.
  • Related