Home > other >  Angular HTML use ngFor index
Angular HTML use ngFor index

Time:11-22

 <div (click)="switchImg($event)" >
      <img
        [ngStyle]="imgs.img1.zero.style"
        id="1"
        src="{{ imgs.img1.zero.src }}"
        alt=""
      />
      <img
        [ngStyle]="imgs.img1.one.style"
        id="1"
        src="{{ imgs.img1.one.src }}"
        alt=""
      />
</div>

Is it possible to replicate this div in html in Angular 10 times using ngFor? The index number is needed to fill the id (1,2,3,4..) and also the properties ngStyle and src. For example ngStyle for first img is imgs.img1.zero.style so I would like to replace the "1" with index so the next two for example should be imgs.img2.zero.style imgs.img3.zero.style. So to give full picture second div should look like this

 <div (click)="switchImg($event)" >
      <img
        [ngStyle]="imgs.img2.zero.style"
        id="2"
        src="{{ imgs.img2.zero.src }}"
        alt=""
      />
      <img
        [ngStyle]="imgs.img2.one.style"
        id="2"
        src="{{ imgs.img2.one.src }}"
        alt=""
      />
</div>

CodePudding user response:

wrap div with ng-container

    <ng-container *ngFor="let index of indexes>
       *your div here*
    </ng-container>

where indexes is array of numbers (1, 2, 3, 4...10) and then use the index as you want

but it would be better if you have array of objects and inside objects you would have style, src and all the other property which you want for image

like so:

[
   {
     style: '',
     src: ''
   },
   {
     style: '',
     src: ''
   }
]

also if you are using property as a img src, insted of this:

src="{{ imgs.img1.zero.src }}"

you can use it like this:

[src]="imgs.img1.zero.src"
  • Related