2017-07-17 31 views
0

试图实现与角Angular2自动建议给予明确的值

$ npm install ng2-auto-complete --save 

地图添加和包装自动建议到systemjs.config.js

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

添加的组件

@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); 
      } 


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

在person.component.html中添加标签

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

这里在下拉菜单中显示未定义的(undefined)。 enter image description here

另外我怎样才能改变这一点,以便每次都会从服务器端获取数据。

回答

2

使用对象而不是字符串时,您需要使用list-formatter属性来调用值格式化程序。

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

,并定义为listFormatter

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

这里是一个工作Plunker例如与您的代码。


  • 还怎么我可以改变这一点,所以,每次将获取从服务器端的数据?

可以使用valueChanged属性将其绑定到从服务器获取数据的功能,虽然这是一个完全独立的问题。

+0

在提及的文档中:valueChanged/ngModelChange,选择新下拉列表时执行的回调函数。例如(valueChanged)=“myCallback($ event)” - 在输入时从下拉列表中选择新值时调用。 – Rosh

+0

是的,是不是你想要的?你在你的回调函数中调用服务器! –

+0

不,不在Onselect上,它的按键更多 – Rosh