Angular material2与复杂对象列表的自动完成绑定不会按预期运行

时间:2017-04-10 14:11:47

标签: angular angular-material

与复杂对象的自动完成绑定不会按预期运行。我想将自动完成绑定到复杂对象列表并将选定的复杂对象分配给另一个,但是当我这样做时,它会在自动完成中显示[对象对象]。我还创建了plunker来说明问题

目前它仅适用于字符串的数组列表。而不是带有普通字符串列表的绑定列表将其与复杂对象列表绑定。

我正在使用Angular Material v2.0.0-beta.3 Plunker Link

1 个答案:

答案 0 :(得分:6)

它的确如documentation中所述。关键是使用displayWith(onSelect)来处理对象选择,如下所示。

HTML:

<md-input-container>
  <input type="text" mdInput [formControl]="searchControl" [mdAutocomplete]="usersComp"/>
</md-input-container>

<md-autocomplete #usersComp="mdAutocomplete" [displayWith]="getDisplayFn()">
  <md-option *ngFor="let user of filteredOptions | async" [value]="user" (onSelect)="selected(user)">
    {{user.displayName}}
  </md-option>
</md-autocomplete>

组件:

export class UserSelectComponent implements OnInit {
  @Input() value: any;
  @Output() valueChange = new EventEmitter();

  searchControl: FormControl = new FormControl();
  filteredOptions: BehaviorSubject<any[]> = new BehaviorSubject(undefined);

  constructor(private api: ApiService) {
    this.searchControl.valueChanges.subscribe(data => {
      if (typeof data === 'string' && data.trim() !== '') {
        this.filter(data);
      }
    });
  }

  ngOnInit() {
    this.searchControl.setValue(this.value ? this.value : '');
  }

  private filter(search: string) {
    this.api.get(`search/user/${search}`).subscribe(data => this.filteredOptions.next(data));
  }

  private getDisplayFn() {
     return (val) => this.display(val);
  }

  private display(user): string {
     //access component "this" here
     return user ? user.displayName : user;
  }

  private selected(user) {
    this.value = user;
    //send to parent or do whatever you want to do
    this.valueChange.emit(user);
  }
}