如何用与材料成角度的API编写自动完成功能

时间:2019-08-28 07:58:25

标签: angular autocomplete angular-material

我尝试用棱角分明的材料来书写。它不起作用,
我拥有所有公司,但是自动完成功能根本无法正常工作。
我也写了一个异步管道,但是我一直都在

  

InvalidPipeArgument:管道“ AsyncPipe”的“ [object Object]”

html:

<div class="container">
  <mat-card>
    <mat-card-title>find company</mat-card-title>
    <mat-card-content>
      <mat-form-field>
        <input type="text" matInput aria-label="company" [formControl]="myControl" [matAutocomplete]="auto" />
      </mat-form-field>

      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let company of companies | async" [value]="company.name"> {{ company.name }} </mat-option>
      </mat-autocomplete>
    </mat-card-content>
  </mat-card>
</div>

我的component.ts:

import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { startWith, map } from 'rxjs/operators';


export class MainComponent implements OnInit {
  companies;
  filterOption: Observable<any[]>;

  observable: Observable<string>;
  myControl = new FormControl();

  constructor(private service: AuthService) {}

  ngOnInit() {
    this.getCompanies();
  }

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

  //   return this.companies.filter(companies => companies.toLowerCase().includes(filterValue));
  // }

  getCompanies() {
    this.service.getCompanyFromApi().subscribe(companies => {
      this.companies = companies;
      this.filterOption = this.myControl.valueChanges.pipe(
        startWith(''),
        map(companies => {
          return this.filter(companies);
        })
      );

      console.log('before component ' + JSON.stringify(companies));
    });
  }
  private filter(value: string): string[] {
    const filterValue = value.toLowerCase();

    return this.companies.filter(company => company.toLowerCase().includes(filterValue));
  }
}

2 个答案:

答案 0 :(得分:0)

尝试

  private filter(value: string): string[] {
        const filterValue = value.toLowerCase();        
        return this.companies.filter(company => company.name.toLowerCase().includes(filterValue));
      }

答案 1 :(得分:0)

您需要将required init?(coder aDecoder: NSCoder)移至Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.clear(); c.set(2016, 4, 22); //your date long time1= c.getTimeInMillis(); c.set(1601, 0, 1); long time2= c.getTimeInMillis(); long ldap = (time1- time2) * 10000; ,并且在HTML中,您需要循环遍历filterOption而不是ngOnInit,以便仅将过滤后的值显示在下拉菜单。当前设置UI的方式是,您要遍历filterOption而不是companies,因此希望所有companies都会显示出来。

filterOption

然后在您的HTML中

companies