Angular6材质:垫子自动完成显示不显示所选对象

时间:2018-08-22 22:02:11

标签: angular autocomplete angular-material2 angular-reactive-forms

我有一个垫子自动完成列表框。问题是当我从列表框中选择任何选项时,它在输入框中没有显示任何内容。

  <form [formGroup]="SForm" id="Form" style="width:100%;height:70%" (ngSubmit)="onSubmit()">
      <mat-form-field>
    <input type="text" placeholder="Direction" aria-label="Assignee"  formControlName="direction" matInput [matAutocomplete]="auto">
     <mat-autocomplete #auto="matAutocomplete" placeholder="Direction" 
     [displayWith]="displayFn">
    <mat-option *ngFor="let directions of filteredDirectionList | async" 
    [value]="directions.value">{{directions.name}}</mat-option>                                            
    </mat-autocomplete>
    </mat-form-field>                       
    </form>

下面是.ts文件

// .ts file

   export const directionList: Array<any> = [{ name: 'Inbound', value: 'I' 
  }, { name: 'Outbound', value: 'O' }];

 ngOnInit() {
  this.SForm= this.formBuilder.group({
  direction: [null],
   });
       this.filterLists();
  }

 displayFn(direction?: any) : string | undefined {
return direction ? direction.name : undefined;;
}

 filterLists() {
this.filteredDirectionList = 
 this.SForm.controls.direction.valueChanges.pipe(
  startWith<string | any>(''),
  map(value => typeof value === 'string' ? value : value.name),
  map(name => name ? this._filter(name, directionList) : 
 this.directionList.slice())
  );
 }

 private _filter(name: string, lists: any[]): any[] {
const filterValue = name.toLowerCase();

return lists.filter(option => option.name.toLowerCase().indexOf(filterValue) 
 === 0);
 }

下面是显示的自动完成列表框

Listsbox

但是在选择时,我没有显示名称。

No display name

也没有控制台日志错误。 我缺少的东西。

Env:angular6,TS 2.7.2,材料6.2.0

1 个答案:

答案 0 :(得分:0)

displayWith函数的参数是使用选项的value输入设置的对象或变量。在您的情况下,您将'directions.value设置为选项值,但是期望Directions对象本身。改变它。简单的解决方案是使用[value]="directions",但是您可能需要更改表单的工作方式,因为表单控件的值现在将是同一对象,而不是值成员。