首页 > 解决方案 > 自动完成组件中的 2 路数据绑定

问题描述

我有 2 个输入文件:

1)课程(即过滤自动完成组件)
2)金额(即输入组件),如下图所示:

在此处输入图像描述

在这里,我想执行 2 路数据绑定。i,e 如果我更改Course名称,Amount则应根据Course. 我怎样才能做到这一点?

这是stackblitz链接。

标签: angulartypescriptangular-materialangular6

解决方案


可以在组件上创建一个键值字典,在下一个方式

选项:{(选项:字符串):数字} = {'数学':20000,'物理':20000,'生物学':20000};

使用 Object.keys 获取自动完成输入并添加选定选项绑定以存储选定选项。

@Component({
  selector: 'autocomplete-filter-example',
  templateUrl: 'autocomplete-filter-example.html',
  styleUrls: ['autocomplete-filter-example.css'],
})
export class AutocompleteFilterExample implements OnInit {
  myControl = new FormControl();
  options: {(option:string):number} = { 'Maths': 20000, 'Physics': 20000, 'Biology': 20000};
  filteredOptions: Observable<string[]>;
  selectedOpt: string;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );
  }

  private _filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return Object.keys(this.options).filter(option => option.toLowerCase().includes(filterValue));
  }
}

您可以绑定值的数量

选项[selectedOpt]

从字典中获取默认值并设置输入

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Courses" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" [(ngModel)]="selectedOpt">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

 <mat-form-field>
    <input matInput placeholder="Amount" [value]="options[selectedOpt]">
  </mat-form-field>

推荐阅读