Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple field for AutoComplete box (primeng 4.2.0 and Angular 4)

How do i display multiple field within a primeng auto complete box.

for example:

<p-autoComplete [(ngModel)]="val" [suggestions]="results" (completeMethod)="search($event)" field="name,lastname"></p-autoComplete>

or 
<p-autoComplete [(ngModel)]="val" [suggestions]="results" (completeMethod)="search($event)" field="name+' '+lastname"></p-autoComplete>

But this does not work.When ever i pass 2 values within a field property as shown above, it does not display any value in the user interface, where as for a single value it works perfectly fine

(example:-field="name")

.

like image 905
Dipin raman Avatar asked Oct 27 '17 10:10

Dipin raman


2 Answers

I guess you could use Templating to do this. See https://www.primefaces.org/primeng/#/autocomplete

<p-autoComplete [(ngModel)]="user" >
    <ng-template let-user pTemplate="item">
        <div class="ui-helper-clearfix">
            {{user.name}}, {{user.lastname}}</div>
        </div>
    </ng-template>
</p-autoComplete>
like image 60
Johannes Klapwijk Avatar answered Oct 07 '22 21:10

Johannes Klapwijk


I think it isn't possible at this moment: https://github.com/primefaces/primeng/issues/1202

But you can bypass the problem adding a calculated field to your object

For example, your class user:

class User {
  name : string; lastname : string;
  description : string;
}

You method (completeMethod) would be:

f(like : string) {
  ...
  users.forEach(_ => { description = lastname + ", " + name} );
  ...
}

And your html template

<p-autocomplete field="description" ...>
  <ng-template let-users pTemplate="item">
    <div class="ui-helper-clearfix">
        {{user.name}}, {{user.lastname}}</div>
    </div>
  </ng-template>
</p-autocomplete>

Or better, you can create a AutocompleteUser object:

class AutocompleteUser {
  user : User;
  description : string;
  constructor(user : User) {
    this.user = user;
    description = ...;
  }
}

In your (completeMethod),

completeMethod(like : string) : void {
  this.service.getUsers()
  .subscribe((users: User[]) => {
    this.autocompleteUsers = users.map((_ : User) => new AutocompleteUser(_) );
  });
}

An then in the template:

[suggestions]="autocompleteUsers"
like image 43
user721730 Avatar answered Oct 07 '22 21:10

user721730