Using ngFor to connect input with the Algolia Places feature

I have implemented an Algolia Places input within an ngFor loop using Angular8. The issue I am facing is that the (change) event only works properly after typing in the input for the second time. While this is functional, it's not exactly the behavior I desire.

It seems like the connection between the function and the input is not automatically established when the input is created. I would like to know how to successfully link the input with the function - any suggestions?

Here is the HTML part:

<ng-container *ngFor="let place of places; let i = index;">
<input id="{{ 'inputaddress' + i}}" (change)="addressSearchIndex(i)" type="text" class="form-control" />
</ng-container>

And here is the Component.ts part:

addressSearchIndex(index) {
        this.placesAutocompleteAddress = placesAlgolia({
            appId: <ID>,
            apiKey: <Key>,
            container: document.querySelector('#inputaddress'+index),
            templates: {
                value: function(suggestion) {
                    return suggestion.name;
                }
            }
        }).configure({
            type: 'address'
        });
        this.placesAutocompleteAddress.on('change', function resultSelected(e) {
            this.lat = e.suggestion.latlng["lat"];
            this.lng = e.suggestion.latlng["lng"];
        });
    }

Answer №1

Consider using keypress or keydown events in place of the change event

Answer №2

Apologies for the delayed response and thank you for your valuable time.

I reached out to Algolia Support (big shoutout to them) regarding my issue, and they were able to resolve it. Here's how you can fix it:

home.component.html :

<app-places type="address" (onChange)="onSuggestion($event)" (onClear)="onClear($event)"></app-places>

place.component.ts :

import {
  AfterViewInit,
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnChanges,
  Output,
  SimpleChanges,
  ViewChild
} from "@angular/core";
import * as places from "./places.min.js";

@Component({
  selector: "app-places",
  template: `
   <input #input class="form-control" type="search" />
  `
})
export class PlacesComponent implements AfterViewInit, OnDestroy, OnChanges {
  private instance = null;

  @ViewChild("input", {static: false}) input;
  @Output() onChange? = new EventEmitter();
  @Output() onClear? = new EventEmitter();

  @Input() type: string;

  ngAfterViewInit() {
    this.instance = places({
      appId: <ID>,
      apiKey: <KEY>,
      container: this.input.nativeElement,
      type: this.type
    });
    this.instance.on("change", e => {
      this.onChange.emit(e);
    });

    this.instance.on("clear", e => {
       this.onClear.emit(e);
     });
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes.type && this.instance) {
      this.instance.configure({
        type: changes.type.currentValue
      });
    }
  }
  ngOnDestroy() {
    this.instance.removeAllListeners("change");
    this.instance.removeAllListeners("clear");
    this.instance.destroy();
  }
}

A huge thank you to Algolia Support for their prompt and friendly assistance.

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

Can a unique custom command be designed for the Kendo UI Grid in Angular2?

The built-in commands supported by the KendoUI Grid for Angular2 include: kendoGridAddCommand kendoGridCancelCommand kendoGridEditCommand kendoGridRemoveCommand kendoGridSaveCommand However, I am working on a project that requires a custom command to be ...

A guide on dynamically adding a CSS stylesheet to an Angular component during runtime

I have a requirement to dynamically inject a stylesheet into a component at runtime. The CSS url needs to change depending on user configuration settings and the selected theme. Using styelUrls for static injection won't work in this case, as it is s ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

Applying CSS styles to a shadow DOM element will not produce the desired visual

I'm encountering an issue while attempting to apply CSS to an element within a shadow-root by adding a class to it. In my Angular component, I have the following code: CSS .test { border: 1px solid red; } TS document.getElementById('my-div&a ...

Angular is a powerful framework that enables the creation of dynamic user interfaces. One of its many

Looking to implement a Material table with expandable rows in Angular. table-tree.html <table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8" > <ng-container matColumnDef="{{co ...

How can I iterate over a specific range in Angular (version 12 and higher) instead of looping through the entire array?

I need help with working with an array called bars stored in a foo property. In my HTML template, I am able to loop through the array like this: <div *ngFor="let bar of foo.bars"> <!-- do something with bar --> </div> Howeve ...

Determine the output type of a function in Typescript using an input value specified by an enum

I am currently saving settings to local storage and want to be able to input responses when retrieving (and possibly inserting) values from/to the storage. After researching, it seems that using function overloading is the best approach. Here is what I ha ...

Error in TypeScript logEvent for Firebase Analytics

Currently utilizing firebase SDK version 8.0.2 and attempting to record a 'screen_view' event, encountering an error message stating: Error: Argument of type '"screen_view"' is not assignable to parameter of type '" ...

The specified path is not found within the JsonFilter

Something seems off. I'm using Prisma with a MongoDB connection and attempting to search the JSON tree for specific values that match the [key, value] from the loop. However, I haven't made much progress due to an error with the path property. Be ...

Is it considered appropriate to return null in a didReceiveResponse callback function?

In my implementation, I have a callback called didReceiveResponse within a class that extends RESTDataSource. In this method, I return null when the response status is 404. However, due to the typing definition of RESTDataSource.didReceiveResponse, it seem ...

Does the Typescript compiler sometimes skip adding braces?

I am encountering a problem with compiling a specific section of code in my Angular2 project. public reloadRecords() { let step = (this.timeInterval.max - this.timeInterval.min) / this.recordsChartSteps; let data = new Array(this.recordsChartSteps ...

Visual Studio - Error TS1005 'Unexpected token'

After spending nearly 5 hours scouring the internet for a solution, I am still unable to resolve this persistent issue. The responses I've found so far do not seem to address the specific problem I'm facing. Although I have upgraded the tsc vers ...

Why is my ASP.NET Core Crud request failing with incorrect method matching?

I am facing an issue with the third method in my Angular ASP.NET Core Controller. The first two methods work fine, but the GetBookItemsByTitle does not seem to be firing correctly. As I am still learning, I believe my mistake here is obvious. /// <summ ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

When transitioning the Next application to Typescript, errors are displayed with JSX, but it functions correctly in the browser

After migrating my Next App from JS to TSX, I noticed that the JSX in my TSX file is showing errors and underlined, even though the app runs fine in the browser. I'm puzzled as to why this inconsistency exists. Can anyone provide assistance in resolvi ...

Tips for refreshing the appearance of a window in angular when it is resized

I have a chat feature integrated into my application. I am looking to dynamically resize an image within the chat window when the width of the window falls below a certain threshold. Is there a method available to modify the CSS style or class based on the ...

Error: The specified path in the MEAN stack must be either a string or Buffer

I am currently utilizing Angular 5 on the front-end, Node for back-end operations, and MongoDB as the database. My current challenge involves attempting to save an image to the database, but I keep encountering an error. Determining whether the issue lies ...

How can you determine the number of times a particular digit appears around a specific position in a TypeScript array

(Utilizing Typescript for assistance) I am looking to determine the number of occurrences of the digit 2 surrounding a specific position within an array. The function takes in the position coordinates as parameters - param 1 for row and param 2 for column. ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

Binding textarea data in Angular is a powerful feature that allows

I am looking to display the content from a textarea on the page in real time, but I am struggling to get the line breaks to show up. Here is my current code snippet: app.component.html <div class="ui center aligned grid">{{Form.value.address}}< ...