Skip to content

Commit

Permalink
fix(typeahead): reset active index when results change
Browse files Browse the repository at this point in the history
Fixes #2303

Closes #2312
  • Loading branch information
pkozlowski-opensource committed Apr 13, 2018
1 parent 91c166d commit 46a4b3b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/typeahead/typeahead-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,15 @@ export class NgbTypeaheadWindow implements OnInit {
this._activeChanged();
}

select(item) { this.selectEvent.emit(item); }

ngOnInit() {
resetActive() {
this.activeIdx = this.focusFirst ? 0 : -1;
this._activeChanged();
}

select(item) { this.selectEvent.emit(item); }

ngOnInit() { this.resetActive(); }

private _activeChanged() {
this.activeChangeEvent.emit(this.activeIdx >= 0 ? this.id + '-' + this.activeIdx : undefined);
}
Expand Down
22 changes: 22 additions & 0 deletions src/typeahead/typeahead.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,28 @@ describe('ngb-typeahead', () => {
expectWindowResults(compiled, ['one', 'one more']);
});

it('should reset active index when result changes', () => {
const fixture = createTestComponent(`<input type="text" [ngbTypeahead]="find"/>`);
const compiled = fixture.nativeElement;

changeInput(compiled, 'o');
fixture.detectChanges();
expectWindowResults(compiled, ['+one', 'one more']);

// move down to highlight the second item
let event = createKeyDownEvent(Key.ArrowDown);
getDebugInput(fixture.debugElement).triggerEventHandler('keydown', event);
fixture.detectChanges();
expectWindowResults(compiled, ['one', '+one more']);
expect(event.preventDefault).toHaveBeenCalled();

// change search criteria to reset results while the popup stays open
changeInput(compiled, 't');
fixture.detectChanges();
expectWindowResults(compiled, ['+two', 'three']);
});


it('should properly make previous/next results active with down arrow keys when focusFirst is false', () => {
const fixture = createTestComponent(`<input type="text" [ngbTypeahead]="find" [focusFirst]="false"/>`);
const compiled = fixture.nativeElement;
Expand Down
1 change: 1 addition & 0 deletions src/typeahead/typeahead.ts
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ export class NgbTypeahead implements ControlValueAccessor,
if (this.resultTemplate) {
this._windowRef.instance.resultTemplate = this.resultTemplate;
}
this._windowRef.instance.resetActive();

// The observable stream we are subscribing to might have async steps
// and if a component containing typeahead is using the OnPush strategy
Expand Down

0 comments on commit 46a4b3b

Please sign in to comment.