Skip to content

Commit

Permalink
fix(rating): changing [max] doesn't update displayed number of stars
Browse files Browse the repository at this point in the history
fixes issue described in #4132
  • Loading branch information
donalfenwick authored and maxokorokov committed Apr 5, 2022
1 parent 4352460 commit 9b49136
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
20 changes: 20 additions & 0 deletions src/rating/rating.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,26 @@ describe('ngb-rating', () => {
expect(ratingEl.nativeElement.getAttribute('tabindex')).toEqual('-1');
});

it('should contain the correct number of stars when [max] is changed', () => {
const fixture = createTestComponent('<ngb-rating [max]="max"></ngb-rating>');

fixture.componentInstance.max = 12;
fixture.detectChanges();

const totalStars = fixture.debugElement.queryAll(By.css('.sr-only')).length;
expect(totalStars).toBe(12);
});

it('should reduce the rating when [max] is changed to a value lower than the current rating', fakeAsync(() => {
const fixture = createTestComponent('<ngb-rating [(rate)]="rate" [max]="max"></ngb-rating>');

fixture.componentInstance.max = 2;
fixture.detectChanges();
tick();

expect(fixture.componentInstance.rate).toBe(2);
}));

describe('keyboard support', () => {

it('should handle arrow keys', () => {
Expand Down
14 changes: 13 additions & 1 deletion src/rating/rating.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,10 +177,13 @@ export class NgbRating implements ControlValueAccessor,
if (changes['rate']) {
this.update(this.rate);
}
if (changes['max']) {
this._updateMax();
}
}

ngOnInit(): void {
this.contexts = Array.from({length: this.max}, (v, k) => ({fill: 0, index: k}));
this._setupContexts();
this._updateState(this.rate);
}

Expand Down Expand Up @@ -218,4 +221,13 @@ export class NgbRating implements ControlValueAccessor,
this.contexts.forEach(
(context, index) => context.fill = Math.round(getValueInRange(nextValue - index, 1, 0) * 100));
}

private _updateMax() {
if (this.max > 0) {
this._setupContexts();
this.update(this.rate);
}
}

private _setupContexts() { this.contexts = Array.from({length: this.max}, (v, k) => ({fill: 0, index: k})); }
}

0 comments on commit 9b49136

Please sign in to comment.