angular - 自动完成输入以在 FormGroup 中过滤更多选项

标签 angular autocomplete angular-material

我需要实现一个简单的自动完成文本框,允许从按名称过滤和显示的对象列表中进行选择。

例如,我有一组具有某些属性(countryName、countryCode、countryId 等)的 Country 对象,我想在文本框中按 countryName 显示和过滤,但是一旦用户选择了国家我想要整个对象被选中。

我可以用 [(ngModel)]FormControl 解决这个问题,但现在我必须使用 FormGroup 我想不通了解如何使用属性 formControlName="..."

这是片段示例:

.html

<form [formGroup]="formGroup">
 [...]
  <mat-form-field>
    <input type="text" placeholder="{{'BIRTH_COUNTRY'|translate}}" matInput formControlName="birthCountry"
      [matAutocomplete]="auto" required>
    <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let country of countries" [value]="country">
        {{country.CountryName}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

.ts

export class PersonalDataComponent implements OnInit {
  public formGroup: FormGroup;

  countries?: Country[];

  constructor(public service: RegisterService) {
    this.formGroup = new FormGroup({
      name: new FormControl(null, Validators.required),
      lastName: new FormControl(null, Validators.required),
      gender: new FormControl(null, Validators.required),
      birthDate: new FormControl(null, Validators.compose([Validators.required, legalAgeValidator])),
      birthCountry: new FormControl(null, Validators.required),
    });

    displayFn(country ?: Country): string | undefined {
      return country ? country.CountryName : undefined;
    }

  }
}

是否有使用自动完成文本框/选择来过滤对象列表并将所选元素绑定(bind)到 FormGroup 元素的解决方案?

最佳答案

编辑:

好的,我让它与自动完成一起工作。这是我的代码:

HTML:

        <mat-form-field>
          <input type="text" placeholder="Country" aria-label="Country" matInput formControlName="country"
            [matAutocomplete]="auto">
          <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
            <mat-option *ngFor="let country of filteredCountries | async" [value]="country">
              {{country.name}}
            </mat-option>
          </mat-autocomplete>
        </mat-form-field>

TS: 在@Component 之前

import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
import { FormBuilder, Validators } from '@angular/forms';
export interface Country {
  name: string;
  id: string;
}

在构造函数之前:

 public formGroup;
 countries: Country[] = [{"name": 'Greece', "id": "1"}, {"name": 'Italy', "id": "2"}, {"name": 'Spain', "id": "3"}]
 filteredCountries: Observable<Country[]>;

构造函数:

constructor(public formBuilder: FormBuilder)

在构造函数之后:

this.formGroup =  this.formBuilder.group({
country: ['', Validators.required]});

在 ngOnInit 上:

 this.filteredCountries = this.formGroup.get('country').valueChanges
      .pipe(
        startWith<string | Country>(''),
        map(value => typeof value === 'string' ? value : (<any>value).name),
        map(name => name ? this._filter(name) : this.countries.slice())
      );

附加功能:

 displayFn(country?: Country): string | undefined {
    return country ? country.name : undefined;
  }

  private _filter(name): Country[] {
    const filterValue = name.toLowerCase();

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

我使用 Material 文档让它工作,并将它添加到我现有的项目中。如果您发现任何区域引用而不是国家,那是因为那是我项目中的关键字,我提前道歉。这将使值占据整个对象。您可以测试并打印 console.log(this.formGroup.value); 提交。

关于angular - 自动完成输入以在 FormGroup 中过滤更多选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53044766/

相关文章:

angular - 如何使用 Angular Material 6 自动完成数据服务器

javascript - Angular Material 自定义类按钮问题

angular-material - 我应该如何应用自定义的角度 Material 主题?

javascript - Angular 2 - 后备路线不起作用

angular - 如何在 Angular 2 中创建高阶组件

javascript - 隐藏在屏幕后面的意见箱

java - 如何设置 Jcombobox 的智能

html - 禁止在图像 URLS 上使用 403

angular - 此导入包含错误,可能会影响依赖于此 NgModule 的组件

javascript - 将 Algolia Instantsearch.js 与 Autocomplete.js 同步