Search code examples
angularangular2-directivesautosuggest

Angular2 auto suggestion giving undefined value


Trying to implement auto suggestion with angular

 $ npm install ng2-auto-complete --save

add map and packages to systemjs.config.js

 map['ng2-auto-complete'] = 'node_modules/ng2-auto-complete/dist';
 packages['ng2-auto-complete'] = { main: 'ng2-auto-complete.umd.js', ...]

Added the component

@Component({
    selector: 'person',
    templateUrl: 'app/person/person.component.html'
})
export class PersonComponent implements OnInit {
    myForm: FormGroup;   
    staffInfo :  PersonalMastModel[];
    public arrayOfKeyValues2: any[] = [
    {key:1, name:'Key One'}, 
    {key:2, name:'Key Two'}, 
    {key:3, name:'Key Three'},
    {key:4, name:'Key Four'}
  ];
personalData(personName: String): Observable<DepartmentModel[]>{
        let headers = new Headers();        
            if(personName!= undefined){

                headers.append('Content-Type','application/json');
                headers.append('Access-Control-Allow-Origin', '*');
                return this.http.post(AppUtils.GET__MASTER_URL //return a list of department
               ,{personName:personName}
               ,{headers:headers})
               .map(response => response.json())
               .catch(this.handleError);
            }


    }
...............

In person.component.html added the tag

 <input auto-complete [source]="arrayOfKeyValues2"
      [(ngModel)]="model3"
      placeholder="enter text"
      value-property-name="key"
      display-property-name="name"/>selected: {{model3 | json}}<br/><br/>

Here in dropdown its coming as (undefined) undefined. enter image description here

Also How can I change this, So that each time will fetch data from server side.


Solution

  • When using objects instead of strings, you need to use the list-formatter attribute to invoke the value formatter.

     [list-formatter]="listFormatter"
     value-property-name="key"
     display-property-name="name">
    

    and define the listFormatter as

    listFormatter = (data: any) => `<span>(${data.key}) ${data.name}</span>`;
    

    Here is a working Plunker example with your code.


    • Also How can I change this, So that each time will fetch data from server side?

    You can use the valueChanged attribute to bind it to a function that fetches data from the server, though this is an entirely separate question.