I have a Rating Component (Angular) as follows:
import { Component, ChangeDetectionStrategy, Input, NgZone, ApplicationRef} from '@angular/core';
import { Icon } from 'ionic-angular/components/icon/icon';
import { Events } from 'ionic-angular';
//
import { ImageService } from '../../providers/image-service/image-service';
//
@Component({
selector: 'rating',
providers: [Icon],
templateUrl: 'rating.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class RatingComponent {
static readonly RATING_CHANGE: string = 'ratings-changed';
text: string;
private tempscore: number = 0;
//
@Input() public score: number = 0;
@Input() public max: number = 5;
@Input() public cardIndex: number = 0;
@Input() public imageID: any = {};
@Input() public iconFull: string = 'md-thumbs-up';
constructor(private evts: Events, private imgService: ImageService,
private ngZone: NgZone, private appRef: ApplicationRef) {
}
public icons(): string[] {
let step = 1;
this.score = Math.ceil(this.score / step) * step;
let icons = [];
for (let i = 1; i <= this.max; i++) {
//
icons.push(this.iconFull);
}
return icons;
}
public update(index: number) {
this.score = index + 1;
let vote_obj = {
imageid: this.imageID,
vote: this.score
}
this.imgService.vote_image(vote_obj).then((res) => {
if (res['ResponseCode'] != 200) {
console.log(JSON.stringify(res));
//
this.score = 0;
this.ngZone.run(() => {
console.log('score is now: ' + this.score);
this.appRef.tick();
})
} else if (res['ResponseCode'] == 200) {
//
}
})
}
}
The Above Component represents the following HTML:
<ul>
<li *ngFor="let icon of icons(); let i = index" (click)="update(i)"
[ngClass]="{'inactive':score <= i , 'active':score > i}">
<ion-icon [name]="icon"></ion-icon>
</li>
</ul>
There are 2 CSS classes that are supposed to be used for manipulating the DOM.
The ngClass
perfectly renders the icon’s color on CLICK
. That is when I change the score
variable inside the click handler for the first time. But I also require to set the icon color to its default value if the ‘ResponseCode
‘ is other than 200 – therefore resetting the score
variable to its default zero does not update the ngClass
on the DOM
I also tried to update the score variable from inside the ngZone.run()
– but with no result !!
What goes wrong with the code above ?
But if I refresh the page (for example with a pull-to-refresh
handler) the icons are applied with correct CSS. How do I do this without refreshing the page ?
Source: AngularJS
from Angular Questions https://angularquestions.com/2017/10/20/ngclass-does-not-update-dom-in-promise-callback/
via @lzomedia #developer #freelance #web #lzomedia.com
No comments:
Post a Comment