【问题标题】:Autocomplete input for filter more options within FormGroup自动完成输入以过滤 FormGroup 中的更多选项
【发布时间】:2019-04-02 08:11:54
【问题描述】:

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

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

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

这里是 sn-p 示例:

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

  }
}

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

【问题讨论】:

  • 我认为你应该删除 [displayWith]="displayFn" 并参考这个link
  • 我已经尝试遵循 Angular 的文档,但它只解决了 [formControl] 的问题,而不是整个表单组的问题...我的意思是有一个 formControName="..." 的示例,但不能不要将它应用于我的问题...我必须管理整个对象,而不仅仅是文档中的单个字符串

标签: angular autocomplete angular-material


【解决方案1】:

编辑:

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

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

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

【讨论】:

  • 我已经尝试过这个解决方案,不幸的是没有任何改变.. 但无论如何这是以简化方式定义表单组的正确方法
  • 您可以尝试 mat-select 而不是自动完成。它绝对适用于我以前使用过的对象。然后,您可以使用输入通过带有 *ngFor="let country of filteredCountries | async" 的 javascript 过滤选择选项,如自动完成文档 (material.angular.io/components/autocomplete/overview)。我会亲自尝试并很快回复您。
  • 好的,如果您需要更多信息,请告诉我。我也试过 mat-select ,但它似乎不支持我需要的那种自动完成......它只是在打字时将焦点移到列表的元素上,但我需要对该列表进行强大的过滤跨度>
  • 查看我的编辑并告诉我您是否还有其他需要整理的内容
  • 它似乎工作得很好,至少我知道从哪里开始!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-05-01
  • 2021-12-25
  • 2020-11-16
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多