来自 API 的 Angular Material 自动完成

Bar*_*sha 8 autocomplete angular-material angular

我尝试从 api 使用自动完成,但它不起作用。它只有在没有 api 的情况下才能工作。

这是我的组件 TS:在那里,有一个带有来自 api (onGetTaxList) 的数据的回调方法

import { Component, OnInit } from '@angular/core';
import { UsersService } from '../../../../core/services/users.service';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';

@Component({
  selector: 'app-create-process-modal',
  templateUrl: './create-process-modal.component.html',
  styleUrls: ['./create-process-modal.component.sass']
})
export class CreateProcessComponent implements OnInit {
  myControl = new FormControl();
  options = [
    { name: 'One' },
    { name: 'Two' },
    { name: 'Tree' },
  ];
  filteredOptions: Observable<any>;


  constructor(private service: UsersService) { }

  ngOnInit() {
    this.service.createNewProcess((data) => this.onGetTaxList(data));
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );
  }

  onGetTaxList(data) {
    console.log(data);
  }
  private _filter(value: string) {
    const filterValue = value.toLowerCase();

    return this.options.filter(option => option.name.toLowerCase().includes(filterValue));
  }
}
Run Code Online (Sandbox Code Playgroud)

组件html:

<div class="formContainer">
    <h2 style="text-align: right">New Process</h2>
    <mat-form-field style="text-align: right">
        <input type="text" placeholder="Start Typing..." matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
                  {{option.name}}
                </mat-option>
              </mat-autocomplete>
    </mat-form-field>

</div>
Run Code Online (Sandbox Code Playgroud)

在这种状态下它与对象的工作

options = [
        { name: 'One' },
        { name: 'Two' },
        { name: 'Tree' },
      ];
Run Code Online (Sandbox Code Playgroud)

现在我想从数据 api 中获得它的工作:

0: {companyName: "ziro", cid: "524023240", partners: Array(4)}
1: {companyName: "plus", cid: "524023240", partners: Array(2)}
Run Code Online (Sandbox Code Playgroud)

我需要自动完成过滤器公司名称。谢谢。

小智 13

成分:

  constructor(private service: Service) { 
  this.filteredOptions = this.myControl.valueChanges
        .pipe(
          startWith(''),
          debounceTime(400),
          distinctUntilChanged(),
          switchMap(val => {
            return this.filter(val || '')
          })       
        );
  }

  // filter and return the values
 filter(val: string): Observable<any[]> {
    // call the service which makes the http-request
    return this.service.getData()
     .pipe(
       map(response => response.filter(option => { 
         return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
       }))
     )
   }  
}
Run Code Online (Sandbox Code Playgroud)

服务:

opts = [];

getData() {
  return this.opts.length ?
    of(this.opts) :
    this.http.get<any>('https://jsonplaceholder.typicode.com/users').pipe(tap(data => this.opts = data))
}

Run Code Online (Sandbox Code Playgroud)

要查看完整演示,请查看此链接Stackblitz


cor*_*aro 6

从呼叫数据中不收取所有数据但在服务器端部分数据的最佳方法:呼叫从第一个字母开始

组件无异步

<form class="example-form">
    <mat-form-field class="example-full-width">
      <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of filteredOptions" [value]="option.name">
          {{option.name}}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>
  </form>
Run Code Online (Sandbox Code Playgroud)

.ts 文件

ngOnInit() {
    this.myControl.valueChanges
      .subscribe(value => {
        if(value.length >= 1){
          this.dashboardService.getProductsByName(value).subscribe(response => {
            this.filteredOptions = response;
          });
        }
        else {
          return null;
        }
      })
}
Run Code Online (Sandbox Code Playgroud)


ami*_*rak 1

在你的 ngOnInit 上尝试添加以下内容:

ngOnInit() {
   .
   ..
   ...
   this.options = []; //init the options data.
   this.yourService.getAllCompaniesOrSomething.subscribe((all_companies)=>{
      this.options = all_companies.map((company)=>{ 
                          return {
                                    name:company.companyName
                          } 
                      });//closing the map function.
   });//closing the subscription.
}
Run Code Online (Sandbox Code Playgroud)