【问题标题】:Angular6 material: mat autocomplete displayWith doesnt display selected objectAngular6材料:垫自动完成显示不显示所选对象
【发布时间】:2019-01-29 05:46:44
【问题描述】:

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

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

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

但在选择时我没有得到显示名称。

也没有控制台日志错误。 我错过了一些东西。

环境:angular6,TS 2.7.2,材料 6.2.0

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-19
      • 2019-02-18
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 2018-06-28
      相关资源
      最近更新 更多