12

I would like to fetch data from server using Autocomplete Component with angular2 / material2. (https://material.angular.io/components/component/autocomplete)

ts

  emailCtrl: FormControl;
  filteredEmails: any;

  constructor(
    private companieService: CompanieService,
  ) {
    this.emailCtrl = new FormControl();
    this.filteredEmails = this.emailCtrl.valueChanges
        .startWith(null)
        .map(email => this.filterEmails(email));
  }


  filterEmails(email: string) {
    this.userService.getUsersByEmail(email)
      .subscribe(
        res => {
          return res
        },
        error => {
          console.log(error);
        }
      )
  }

html

    <md-input-container>
      <input mdInput placeholder="Email" [mdAutocomplete]="auto" [formControl]="emailCtrl" [(ngModel)]="fetchedUser.profile.email">
    </md-input-container>

    <md-autocomplete #auto="mdAutocomplete">
      <md-option *ngFor="let email of filteredEmails | async" [value]="email">
        {{email}}
      </md-option>
    </md-autocomplete>

Service: userService.getUsersByEmail(email) is pulling this kind of data:

 ['email1@email.com','email2@email.com','email3@email.com']

I have no errors but no results in the autocomplete. I see in debugger of chrome (tab network) Data are pulled correctly for each changes in the input

Edric
  • 24,639
  • 13
  • 81
  • 91
Alan
  • 9,167
  • 4
  • 52
  • 70
  • Any way to make it show all available when the user clicks into the input box instead of waiting for the first letter to be typed? – Kyle Krzeski Oct 27 '17 at 02:24

3 Answers3

14

ill give you my example that i usually use,

this.SearchForm.controls['city_id'].valueChanges
  .debounceTime(CONFIG.DEBOUNCE_TIME)
  .subscribe(name => {
    this.domain = [['name', 'ilike', name]];
    this.DataService.getAutoComplete('res.city', this.domain)
      .subscribe(res => {
        return this._filteredCity = res['result']['records']
    })
  })

HTML

<div class="mb-1 ml-1 mt-1" fxFlex="30">
  <md-input-container style="width: 100%">
    <input mdInput placeholder="Kota" (blur)="checkAutoComplete('city_id')" [mdAutocomplete]="city_id" [required]="true" [formControl]="SearchForm.controls['city_id']">
  </md-input-container>
  <md-autocomplete #city_id="mdAutocomplete" [displayWith]="displayFn">
    <md-option *ngFor="let city of _filteredCity" [value]="city">
      <span>{{ city.name }}</span>
    </md-option>
  </md-autocomplete>
  <div *ngIf="SearchForm.controls['city_id'].hasError('required') && SearchForm.controls['city_id'].touched" class="mat-text-warn text-sm">Kolom ini wajib diisi.</div>
</div>

just like that

Sonicd300
  • 1,950
  • 1
  • 16
  • 22
kazuyahiko
  • 343
  • 2
  • 13
  • Any way to make it show all available when the user clicks into the input box instead of waiting for the first letter to be typed? – Kyle Krzeski Oct 27 '17 at 00:41
3

This is how i done.

.html

       <input formControlName="search" [mdAutocomplete]="auto" type="text" class="form-control">
 <md-autocomplete #auto="mdAutocomplete">
     <md-option *ngFor="let data of filteredData | async" [value]="data.text">
    {{ data.text }}
     </md-option>
 </md-autocomplete>

.ts

 filteredData: Observable<any[]>; // async pipe needs to be an Observable
 myContent: any[] = [];

 this.filteredData = this.myformGroup.get('search').valueChanges
 .debounceTime(400)
 .switchMap(value => {

  // get data from the server. my response is an array [{id:1, text:'hello world'}] as an Observable
  return  this.myApiService.getSearch(value); 

}).map(res => this.myContent = res);

let me know if this works for you.

Robin
  • 605
  • 7
  • 28
  • 1
    Search is not live in this solution, the results shown based on previous search key... – Sreekumar P Jul 13 '17 at 11:00
  • No its not previous, since if you want to make a request on each keyup value, just remove this: `let exist = this.myContent.findIndex(t => t.text === value); if (exist > -1) return;` – Robin Jul 13 '17 at 15:18
  • - Instead of `do` you should use `switchMap` to previous ongoing requests and return this.myApiService.getSearch() ( remove subscribe completely from here - Remove delay 500 since switchMap handles our request waiting - then add subcribe which writes straight to this.filteredData. Also remember to unsubscribe or use takeUntil / takeWhile with ngOnDestroy method. – MTJ Mar 27 '18 at 08:08
  • @user1740331 YEP! i've refactored as you mention with `mergeMap` operator instead. – Robin May 15 '18 at 04:35
  • 1
    @Robin mergeMap doesn't stop ongoing API calls your responses arrive in what random order. See marbles on https://stackoverflow.com/a/42227335/1740331 – MTJ May 15 '18 at 06:41
  • @user1740331 Yeah, updated with operator `switchMap` as described on a link you've provided. – Robin May 15 '18 at 08:14
0

my.component.html

<form [formGroup]="myForm">
  <mat-form-field>
    <input matInput
        formControlName="email"
        [matAutocomplete]="autoEmailGroup"
        name="email"
        type="email"
        placeholder="Email"
        aria-label="Email" />
    <mat-autocomplete
        autoActiveFirstOption
        #autoEmailGroup="matAutocomplete">
      <mat-option
          *ngFor="let email of emailOptions | async"
          [value]="email">{{ email }}</mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

my.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

import { Observable } from 'rxjs';
import { startWith, tap, switchMap, map, filter } from 'rxjs/operators';
import { empty } from 'rxjs/observable/empty';

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

  myForm: FormGroup;
  emailOptions: Observable<string[]>;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
  ) { }

  createForm() {
    this.myForm = this.fb.group({
      email: new FormControl(),
    });

    const _fetchEmailsFromServer = (): Observable<string[]> => {
      // TODO you need to ultilize your service here
      return empty();
    };

    this.emailOptions = this.myForm.get('email')!.valueChanges
      .pipe(

        startWith(''),

        switchMap((input: string) => {
          return _fetchEmailsFromServer().pipe(

            // handle your HTTP response here
            map((response: any): string[] => {
              return <string[]> response!.data!.emails;
            }),

            tap((emails: string[]) => {
              // LOGGING
              console.log('Received emails:', emails);
            }),

            // you can filter emails fetched from your server here if you want
          );
        }),

      ).pipe(

        // default value to be displayed before HTTP task is completed
        startWith([]),
      );
  }

}

Reference:

KaiserKatze
  • 1,521
  • 2
  • 20
  • 30