自动完成组件中的双向数据绑定

我有2个输入文件结构:

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

enter image description here

在这里,我想执行双向数据绑定 . i,e如果我更改 Course 名称 Amount 应根据 Course 更改 . 我怎样才能实现这一目标?

这是stackblitz链接 .

回答(3)

2 years ago

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

options:{(option:string):number} = {'Maths':20000,'Physics':20000,'Biology':20000};

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

@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>

2 years ago

请使用以下代码

HTML

<mat-autocomplete #auto="matAutocomplete" (optionSelected)="optionSelected($event, row, column, rowIndex)">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>

<input matInput placeholder="Amount" [(ngModel)]="amount">

在TS

optionSelected(event){
    if(event.option.value == 'Physics')
      this.amount = 2000;
    if(event.option.value == 'Maths')
      this.amount = 5000;
    if (event.option.value == 'Biology')
      this.amount = 10000;
  }

2 years ago

嗨,对于undefined,您只需更改代码段即可

enter code here[value]="options[selectedOpt] == undefined ? '' : options[selectedOpt]"