【问题标题】:Angular Material Autocomplete and API ObjectsAngular Material 自动完成和 API 对象
【发布时间】:2021-01-16 10:48:36
【问题描述】:

我与 Material 的自动完成功能斗争了好几天。我已经使用了这里的大量示例,但仍然无法正常工作。 我想要实现的是从 API 获取用户,将它们加载到自动完成,因为名称应该是可见的,但我想要一个值作为对象。 这是我到目前为止所拥有的:

***API Service:***

export class UserService {
  constructor(private httpClient: HttpClient) {}

  getData() {
    return this.httpClient.get<any>('https://jsonplaceholder.typicode.com/users');
  }
}

***component.ts***

constructor(private usc: BreweryService, private formBuilder: FormBuilder) { 
    this.users = this.usc.getData();
    
  }
  
  ngOnInit() {
    this.form = this.formBuilder.group({
      myControl: ['', Validators.required],
      name: ['', Validators.required]
    });
 
    this.filteredUsers = this.form.controls['myControl'].valueChanges.pipe(
      startWith(''),
      debounceTime(200),
      distinctUntilChanged(),
      switchMap(val => {
        return this.filter(val || '')
        
      })
    )    
}

filter(val: string) {
  return this.users.pipe(
    map(response => response.filter(option => {
      return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
    }))
  )
}

displayFn(user): string {
  return user.name;
}

***html***
<mat-form-field class="example-full-width">
  <mat-label>Assignee</mat-label>
  <input type="text" matInput formControlName="myControl" [matAutocomplete]="auto">
  <mat-autocomplete #auto="matAutocomplete" 
  [displayWith]="displayFn">
    <mat-option *ngFor="let user of filteredUsers | async" 
        [value]="user">
      <span>{{ user.name }}</span>
    </mat-option>
  </mat-autocomplete>  
</mat-form-field>

控制台报错:

"ERROR TypeError: val.toLowerCase 不是函数"

并且自动完成在打字时不起作用。

我创建了stackblitz 来显示问题

【问题讨论】:

    标签: angular autocomplete angular-material angular9


    【解决方案1】:

    你需要这样做

      myControl = new FormControl();
    

    之后

    this.filteredUsers = this.myControl.valueChanges.pipe(
      startWith(""),
      map(value => (typeof value === "string" ? value : value.name)),
      map(name => (name ? this.filter(name) : this.users.slice()))
    );
    

    检查 this.users 是否不为空并返回名称为 in 的对象列表

    并确保filteredUsers 是可观察的

    filter(val: string) {
        const filterValue = name.toLowerCase();
        return this.users.filter(
          option => option.name.toLowerCase().indexOf(filterValue) === 0
        );
    }
    

    希望有用

    【讨论】:

    • 不,它不起作用。我不能使用过滤器,在 Observables 上切片,而且我正在使用 ReactiveForms
    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-19
    • 2018-02-26
    • 2019-10-14
    相关资源
    最近更新 更多