Options in typeahead not visible

Can someone help me with the code I'm currently working on? I successfully retrieved data from a remote service and it shows in the log, but now the typeahead feature is not displaying options when clicked. Any assistance would be appreciated.

I have searched through various blogs and Stack Overflow questions related to this issue but so far, no solutions have worked.

Below is my code snippet:

TypeScript

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: [HomeServiceService]
})
export class HomeComponent implements OnInit {
   title = 'Autocomplete Example in Angular 6';

  

   searchTerm: FormControl = new FormControl();
   myDestination = <any>[];

   constructor (private service: HomeServiceService){

   }


   


  ngOnInit(): void {

    this.searchTerm.valueChanges.subscribe(
      term => {
        if ( term != ''){
          this.service.search(term).subscribe(
            data => {
              this.myDestination = data as any[];
              console.log(this.myDestination)
            
            }
          )
        }

        
      }
    )

service.ts

@Injectable()
export class HomeServiceService {

  constructor(private httpClient : HttpClient) { }

  search(term){

    var listOfBooks = this.httpClient.get('http://192.168.88.250:8080/api/v1/searchterminals/?searchTerm=' + term)
    .pipe(
      debounceTime(500),
      map(
        (data: any) => {
          return (
            data.length != 0 ? data as any[] : [{"BookName" : "No Record Found"} as any]
          );
        }
      )
    )
    return listOfBooks;
  }
  

html

 <mat-form-field class="container" >

          <input type="text" placeholder="Search destination ..."
                matInput 
                [formControl]="searchTerm" 
                [matAutocomplete]="auto">  
  
  
                <mat-autocomplete #auto="matAutocomplete">
  
                  <mat-option *ngFor="let destination of this.myDestination.name" [value]="destination.name">
                      
                      {{ destination.name}}
                      {{ destination.city.name}}
                      
                  </mat-option>

                </mat-autocomplete>
  
      </mat-form-field>

Answer №1

I have observed three issues.

  1. There is a mistake in your .HTML file regarding the *ngFor loop.
    You are iterating over this.myDestination.name, but this property does not exist on the array "myDestination" or the Array class. Remove '.name' from your *ngFor loop for successful iteration. Additionally, be mindful of accessing destination.city.name as it may result in trying to access .name of undefined.

Based on your service.TS file, your array should have the structure [{BookName: string}]. To visualize it correctly:

const myDestination = [{"BookName" : "No Record Found"}]
. Verify in your IDE that neither .name exists as a property nor is it set as a variable in any array items:

https://i.sstatic.net/maBNb.png

This error leads to the second problem I noticed:
2. In your .HTML file, you are attempting to display destination.city.name, which is also non-existent: https://i.sstatic.net/A6sQB.png

  1. In your home.component.ts file, when declaring myDestination, avoid using type any. Instead, specify it like this:
    myDestination: Array<any> = []
    . Learn more about casting here and Type Assertion here.

Understanding these errors will help you realize that Angular relies on sound TypeScript syntax. Check out the official documentation for further insights.

Suggested practices:

  • Name arrays in plural form - myDestinations
  • Avoid using type any if possible.
  • Consider utilizing tools like Angular Language Service to catch errors early on.
  • Apply DebounceTime before making a service call or API request rather than after receiving the response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing multi-select checkbox feature in Angular 7 using ng-select

I'm looking to create a function where selecting an item will make the corresponding div appear. For instance, if I choose Crédit bancaire and Compte courant associé, the two corresponding divs should be shown. Check out this example: https://stac ...

What is the best way to link three different types of http requests in succession and adaptively?

Is it possible to chain together 3 types of http requests correctly, where each request depends on data from the previous one and the number of required requests can vary? In my database, there is a team table with a corresponding businessId, a supervisor ...

Utilize TypeScript to access scope within a directive

Is there a way to access the controller's scope properties using my custom TypeScript directive? For example, in this snippet below, I am trying to retrieve and log scope.message: /// <reference path="typings/angularjs/angular.d.ts" ...

Customizing the appearance of Indicators and Paginator in PrimeNG Carousel

I have integrated a carousel using PrimeNG which has the following design here Take note of the style of the carousel indicators and navigators. I want to achieve the default style of indicators/navigators for the carousel as shown here I have included t ...

Chai expect() in Typescript to Validate a Specific Type

I've searched through previous posts for an answer, but haven't come across one yet. Here is my query: Currently, I am attempting to test the returned type of a property value in an Object instance using Chai's expect() method in Typescript ...

Does angular have a feature comparable to JavaScript's .querySelectorAll()?

I developed an inventory calculator in JavaScript that provides item count based on weight. The calculator has 4 inputs, and now I'm looking to replicate the same functionality using Angular. Is there a method in Angular similar to .querySelectorAll() ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Exploring TypeScript: Understanding how to define Object types with variable properties names

Having an issue with a React + TypeScript challenge that isn't causing my app to crash, but I still want to resolve this lingering doubt! It's more of a query than a problem! My goal is to set the property names of an object dynamically using va ...

Encountering an infinite loop issue with React's useEffect and context: How to solve the "maximum update depth exceeded" console error

Utilizing React Context and a reducer for state management, my objective is to have the application check if a specific state is empty upon user login. If the state is empty, I want it to be filled with a value, and if it already has a string value, then i ...

How is it possible for TypeScript to permit an inaccurate comparison like boolean === undefined?

Encountering the peculiar behavior of TS. const isItLanding = false; if (isItLanding === undefined) { // valid return ...; } However, in this instance const isItLanding = 1; if (isItLanding === 'undefined') { // error return ...; } Why do ...

What are the best practices for handling context in Angular?

Currently, I am focused on enhancing our code base to improve readability and performance. Our approach involves a container component that loads all necessary data and passes it down to child components via Inputs. While this is generally considered good ...

Incorporate a personalized Cypress function for TypeScript implementation

I'm in the process of developing a custom cypress command that will enable me to post a file using formData, as the current cy.request does not yet support formData. For the actual POST operation, I am utilizing request-promise-native. To begin with ...

Overriding Bootstrap Modals with PhaserJS Canvas

I am currently working on a simple game using phaserJs with Angular and styling it with bootstrap. The issue I'm facing is that when I display a bootstrap modal and interact with it, it affects the buttons on my phaserJS canvas. Here is an example pr ...

Tips for applying personalized CSS to the ngbDatepicker component in Angular 4

Here is the HTML code I am working with: <div> <div style="color:white">Date Range:</div> <div class="input-daterange input-group"> <input class="form-control" value="2017-01-01" name="dp1" ...

Can you explain the significance of {a11yProps(0)} within the component property?

Consider this code snippet for a component: ... ... function a11yProps(index: any) { return { id: `simple-tab-${index}`, 'aria-controls': `simple-tabpanel-${index}`, }; } ... ... return ( <div className={classes.root}> ...

Guide to developing a versatile Icon Wrapper component for FontAwesome Icons in React that adapts to changing needs

I'm looking to develop a customized React Icon-Component where I can simply input the icon name as a string and have the icon display automatically. After following the guidelines provided here: https://fontawesome.com/docs/web/use-with/react/add-ico ...

Is it possible to substitute an Angular component with a component from a custom module in a similar fashion to utilizing a decorator in AngularJS?

I am currently working on an application that caters to a diverse customer base. Each customer has unique customization needs for their user interface. We are interested in replacing certain components with customer-specific ones, but have been facing chal ...

Using ReactJS with Typescript and react rewired to load CSS module

I am currently setting up a proof of concept project using ReactJS and typescript, and I want to incorporate CSS modules without ejecting the webpack configuration. Here are the steps I have taken so far: Installed create-react-app globally - npm install ...

What is the process for designing a mapping type that involves two enums?

I need a solution to connect these two types and create mappings: type MappedEnum<T extends string, A extends string, B extends string> = { [key in T]: {[key in A]: B}; [key in T]: {[key in B]: A}; }; enum Greek { ALPHA = 'A', BET ...

NestJS Resolver Problem: Getting an Undefined Error

Could use a bit of assistance. I'm currently working on a mutation and encountering the following error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'entryUser') Here is the resolver code snippet: export class Us ...