如何显示焦点自动完成选项(how to show autocomplete options on f

2019-11-05 05:15发布

:)

我正在写有最新的角材料的应用angular6。

我使用组件mat-autocompletemat-input用于自动完成功能。

我想要实现的是,当用户集中在输入元素上,他会看到所有可用的自动完成选项,即使没有输入任何内容。

这是脚垫,自动完成组件的HTML文件

<form [formGroup]="carTypeFormGroup" (ngSubmit)="okButton()">
  <mat-form-field>
    <input matInput formControlName="carCompany"
           placeholder="foo" aria-label="foo" [matAutocomplete]="autoCarCompany">
    <mat-autocomplete  #autoCarCompany="matAutocomplete">
      <mat-option *ngFor="let carCompany of filteredCarCompanies | async" [value]="carCompany">
        <span>{{carCompany}}</span>
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
...

这是组件的类的代码:

@Component({
  selector: 'app-car-type',
  templateUrl: './car-type.component.html',
  styleUrls: ['./car-type.component.scss']
})
export class CarTypeComponent implements OnInit {

  carTypeFormGroup: FormGroup;

  filteredCarCompanies: Observable<CarType[]>;
  filteredCarModels: Observable<CarType[]>;
  carCompanies = [];
  carCompaniesLowercase = [];
  carModels = [];
  carTypes = [];

 private _filterCarCompanies(value: string): CarType[] {
    if (this.carCompaniesLowercase.indexOf(value.toLowerCase()) >= 0) {
      this.mainGql.GetCarModels(value).subscribe((data: any) => {
        this.carModels = [];
        data.data.car_models.forEach((row) => {
          this.carModels.push(row.model_name);
        });
      });
    }
    const filterValue = value.toLowerCase();
    return this.carCompanies.filter(carCompany => carCompany.toLowerCase().indexOf(filterValue) === 0);
  }

ngOnInit() {
    this.carTypeFormGroup = this.formBuilder.group({
      carCompany: ['', Validators.required],
      carModel: ['', Validators.required],
      carType: ['', Validators.required],
      carYear: [new Date().getFullYear(), Validators.required]
    });
    this.filteredCarCompanies = this.carTypeFormGroup.get('carCompany').valueChanges
      .pipe(startWith(''), map(carCompany => carCompany ? this._filterCarCompanies(carCompany) : this.carCompanies.slice()));
}
...
}

当我检查mat-autocomplete的例子在https://material.angular.io/components/autocomplete/examples ,那里,当我集中输入元素我看到所有的结果上..

有什么不同? 我缺少什么?

谢谢

Answer 1:

当页面加载..但我装上graphql数据,以便执行第一过滤后的数据到达执行过滤器。 我改之以接收到数据后,才滤波器将被执行。

感谢Swoox帮我注意到它。

ngOnInit() {
 ...
 this.carsService.GetCarCompanies().subscribe((data: any) => {
      this.carCompanies = [];
      this.carCompaniesLowercase = [];
      data.data.car_companies.forEach((row) => {
        this.carCompanies.push(row.company_name);
        this.carCompaniesLowercase.push(row.company_name.toLowerCase());
      });
      this.filteredCarCompanies = this.carTypeFormGroup.get('carCompany').valueChanges
        .pipe(startWith(''), map(carCompany => carCompany ? this._filterCarCompanies(carCompany) : this.carCompanies.slice()));
    });


文章来源: how to show autocomplete options on focus