ngOnChanges Angular 2 doesn't assign different values

Issue

I’ve got public value cursorUrl and method which checks if url exists and if it exists it assigns urlCursor='pointer' if it doesn’t exist it assigns urlCursor='text'.

The method seems to work fine, however it assigns every item to urlCursor='pointer' even though console log prints me that it should be

pointer
text
text
text

this is my method:

ngOnChanges(changes: any) {
    let index = 0;
    this.urlCursor = 
        this.checkUrl(changes.items.currentValue[0].redirectionViewUrl);
    index++; 
    console.log(this.urlCursor);
}

and this is html:

<div class="items" #item(window:resize)="itemResizeHandler();" >
    <app-item
        *ngFor="let item of items"
        class="item-element"
        [ngStyle]="{'cursor': urlCursor}"
        [dataMode]="item.dataMode"
        [redirectionViewUrl]="item.redirectionViewUrl"
    ></app-item>
</div>

does anyone have idea why it’s not binding properly?

Solution

Binding works correctly. Your urlCursor is not an array of variables but a single variable, so whatever is assigned to it last will be used for all values. Try to modify your code in ts file like:

public urlCursor: string[] = []
...
ngOnChanges(changes: any) {
    ...
    this.urlCursor = []; 
    this.urlCursor.push(
      this.checkUrl(changes.items.currentValue[0].redirectionViewUrl)
    );
    ...
}

and htlm like:

<app-item
  *ngFor="let item of items; let ind=index"
   class="item-element"
   [ngStyle]="{'cursor': urlCursor[ind]}"
   [dataMode]="item.dataMode"
   [redirectionViewUrl]="item.redirectionViewUrl"
></app-item>

Answered By – Yevgen

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.