How to create variable in ngFor loop?

I think local variables (defined with the # character) don’t apply for your use case. In fact, when you define a local variable on an HTML element it corresponds to the component if any. When there is no component on the element, the variable refers to the element itself. Specifying a value for a local … Read more

how to bind img src in angular 2 in ngFor?

Angular 2, 4 and Angular 5 compatible! You have provided so few details, so I’ll try to answer your question without them. You can use Interpolation: <img src={{imagePath}} /> Or you can use a template expression: <img [src]=”imagePath” /> In a ngFor loop it might look like this: <div *ngFor=”let student of students”> <img src={{student.ImagePath}} … Read more

function gets called several times

The caculateFunction(data.price) function will be called every time Angular runs change detection for the component (more precisely for the embedded view created by ngFor). This is because updating DOM is part of change detection and Angular needs to call caculateFunction to know what value to use for DOM update. And change detection cycle can run … Read more

Angular 2: Callback when ngFor has finished

You can use @ViewChildren for that purpose @Component({ selector: ‘my-app’, template: ` <ul *ngIf=”!isHidden”> <li #allTheseThings *ngFor=”let i of items; let last = last”>{{i}}</li> </ul> <br> <button (click)=”items.push(‘another’)”>Add Another</button> <button (click)=”isHidden = !isHidden”>{{isHidden ? ‘Show’ : ‘Hide’}}</button> `, }) export class App { items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; … Read more

Angular2 Dynamic input field lose focus when input changes

This happens when the array is a primitive type, in your case a String array. This can be solved by using TrackBy. So change your template to match the following: <div *ngFor=”let value of field.values; let i=index; trackBy:trackByFn”> <input type=”text” [(ngModel)]=”field.values[i]” /><br/> </div> <div> <button (click)=”addValue(field)”>Click</button> </div> and in the ts file add the function … Read more

How to use `trackBy` with `ngFor`

On each ngDoCheck triggered for the ngForOf directive, Angular checks what objects have changed. It uses differs for this process and each differ uses the trackBy function to compare the current object with the new one. The default trackBy function tracks items by identity: const trackByIdentity = (index: number, item: any) => item; It receives … Read more