Reputation: 116
I want to use the PrimeNG autocomplete component but it doesn't work as expected. If you type something in the input field, the completeMethod is executed, but the results aren't shown. I tested the completeMethod first and it works fine and filters the array correctly, but the component don't show the suggestion list with my values, instead it shows the loading spinner all the time. After you type something else, press any other key or click elsewhere the results are shown up, but the loading spinner is still there.
I've already searched for solutions, but found nothing useful for my problem. I read there are some common simliar problems with the dropdown click, so i tried to apply these fixes, but it doesn't help me neither.
The Component, which holds the autocomplete, its ChangeDetectionStrategy is set on OnPush
Here is my Code:
Component:
<p-autoComplete
[formControlName]="formName"
[suggestions]="options"
(completeMethod)="filterMethod($event)"
[dropdown]="true"
field="label"
[multiple]="true"
[forceSelection]="true"
[minLength]="3"
(onDropdownClick)="handleDropdownClick($event)"
></p-autoComplete>
Filter Method:
filterMethod(event: { query: string; originalEvent: any }) {
this.service
.getSelectItemsByService(this.id)
.subscribe(options => {
this.options = this.filter(event.query, options).slice();
});
}
private filter(query: string, options: SelectItem[]): SelectItem[] {
return query
? options.filter(value =>
value.label
.toLowerCase()
.trim()
.includes(query.toLowerCase().trim())
)
: options;
}
Thank you in advance!
Upvotes: 3
Views: 4664
Reputation: 116
The Component, which held the autocomplete Component, it‘s ChangeDetectionStrategy was set on OnPush and this caused the problem. Because of that the PrimeNg autocomplete couldn‘t update the view properly.
I solved it by either removing the OnPush strategy and leave it on Default or calling the ChangeDetectorRefs markForCheck() in Observables subscribe.
Upvotes: 0
Reputation: 4782
Created minimal working example with API calling please refer it. Start typing with minimum 3 chars and you will get filtered list with dropdown
<p-autoComplete
[suggestions]="options"
(completeMethod)="filterMethod($event)"
[dropdown]="true"
field="title"
[multiple]="true"
[forceSelection]="true"
[minLength]="3"></p-autoComplete>
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
options = [];
constructor(public http: HttpClient) {
}
filterMethod(event) {
this.http.get('https://jsonplaceholder.typicode.com/todos')
.subscribe(res => {
const result = (<any>res).filter(option => option.title.includes(event.query));
console.log(result);
this.options = result;
});
}
}
You can refer this example: http://keepnote.cc/code/p-auto-complete-with-api-calling-example
Upvotes: 3