Topic: autocomplete initialize with value

mnikam free asked 4 years ago


Initialize autocomplete searchText field with some text, for example name of the logged in user

I followed "Remote Data" section of https://mdbootstrap.com/docs/angular/forms/autocomplete/ to setup autocomplete in our sample app. I was wondering if there is a way to initialize searchText with some text

Remote data section of https://mdbootstrap.com/docs/angular/forms/autocomplete/

ngOnInit(): void { this.searchText.next("alis"); }

I did not see value "alis" in the searchText in UI.


mnikam free answered 4 years ago


I was able to accomplish initialization by changing searchText type from Subject to BehaviorSubject and initializing value in ngOnInit

import { Component, OnInit } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Component({
  selector: 'remote-auto-completer',
  templateUrl: './remote-auto-completer.component.html',
  styleUrls: ['./remote-auto-completer.component.scss'],
})
export class RemoteAutoCompleterComponent {
  searchText = new BehaviorSubject<string>("");
  url = 'https://swapi.co/api/people/?search=';
  results: Observable<any>;
  data: any = [];

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.searchText.next("John");
    this.httpClient.get(this.url).subscribe((data: any) => {
      console.log(data);
      this.data = data;

      this.results = this.searchText.pipe(
        startWith(''),
        map((value: string) => this.filter(value))
      );
    });
  }

  filter(value: string): string[] | undefined {
    const filterValue = value.toLowerCase();
    if (this.data && this.data['results']) {
      return this.data['results'].filter((item: any) =>
        item.name.toLowerCase().includes(filterValue)
      );
    }
  }
}

Arkadiusz Idzikowski staff commented 4 years ago

We will take a closer look at that and update the documentation.



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB Angular
  • MDB Version: 9.4.0
  • Device: Desktop
  • Browser: Google Chrome
  • OS: Windows 10
  • Provided sample code: No
  • Provided link: Yes