Using ngx-bootstrap typeahead with custom itemTemplate for objects

I've created a custom ngx-bootstrap/typeahead component for my ngx-formly generated forms. This component fetches search results from an API and is designed to be reusable for various objects, making it dynamic.

My goal is to have the typeahead retrieve data from an Observable and present the items using a specific template:

<div class="widget form-group">
  <input id="typeahead-basic"
      type="text" class="form-control" autocomplete="off"
      [formControl]="formControl" 
      [formlyAttributes]="field"
      [typeahead]="search$"
      [typeaheadItemTemplate]="autocompleteItem"
      [typeaheadAsync]="true"      
      />
      <!-- Works with typeaheadOptionField="value.nested" -->
</div>

<ng-template #autocompleteItem let-item="item">
  <span>{{ item.value.nested }}</span>
</ng-template>

Here is the Observable setup:

search$ = new Observable((observer: Observer<string>) => {
  observer.next(this.formControl.value);
}).pipe(
  tap(v => console.log('Input: ' + v)),
  switchMap(v =>
    of([
      {value: { nested: "foo"}},
      {value: { nested: "bar"}},
      {value: { nested: "foobar"}}
    ])
    //of(['foo', 'bar', 'foobar'])
  )
);

This configuration previously functioned correctly, but recent upgrades have caused issues that downgrading did not resolve...

To see this in action, visit this StackBlitz link: https://stackblitz.com/edit/angular-h3khea

If you include

typeaheadOptionField="value.nested"
in the code snippet, the functionality returns. However, it appears this value must be hardcoded rather than loaded dynamically from a .ts file.

A similar example demonstrating the desired behavior can be found here: https://stackblitz.com/edit/angular-8t8dcm-kzbw52

The discrepancy between these versions may lie in their use of reactive forms and different Angular versions, which I am hesitant to downgrade to...

Answer №1

Works perfectly in conjunction with typeaheadOptionField:

Utilize it as a "string-setter" and input a property path or even a method name (for a method on the search result object):

typeaheadOptionField="my.property"
// alternatively
typeaheadOptionField="myMethod()"

Moreover, you can bind it to a property by using the correct syntax:

[typeaheadOptionField]="propertyInComponent"

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

The 'substr' property is not found in the type 'string | string[]'

Recently, I had a JavaScript code that was working fine. Now, I'm in the process of converting it to TypeScript. var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; if (ip.substr(0, 7) == "::ffff ...

Removing a dynamic component in Angular

Utilizing Angular dynamic components, I have successfully implemented a system to display toaster notifications through the creation of dynamic components. To achieve this, I have utilized the following: - ComponentFactoryResolve - EmbeddedViewRef - Ap ...

What is the reason behind TypeScript choosing to define properties on the prototype rather than the object itself?

In TypeScript, I have a data object with a property defined like this: get name() { return this._hiddenName; } set name(value) { ...stuff... this._hiddenName = value; } However, when I look at the output code, I notice that the property is on ...

Error message: "Encountered 'Cannot Get' error while building Angular

I encountered an error when trying to run my Angular project in IntelliJ. Upon opening the browser on localhost, I received the message Cannot GET / Here are the steps I followed: Opened up the project Ran npm install -g @angular/cli@latest Ran gradlew c ...

Implementing delayed loading of Angular modules without relying on the route prefix

In my application, I am using lazy loading to load a module called lazy. The module is lazily loaded like this: { path:'lazy', loadChildren: './lazy/lazy.module#LazyModule' } Within the lazy module, there are several routes def ...

How to stop a form from being cleared when a button is clicked in Angular 2

Within my form, there is a button that allows users to add an item to the object's array. <form (ngSubmit)="submit()" #myForm="myForm" class="form-horizontal" style="direction: ltr"> <div class="row"> <div class="col-md-6"> ...

Guide on integrating msw with Next.js version 13.2.1 (Issue: Unable to access worker.start on the server)

I'm currently in the process of integrating a simulated API that sends back a response object containing a series of messages meant to be displayed in the UI (specifically, a chatbox) alongside the username, user picture, and other relevant informatio ...

The parameter cannot be assigned the readonly type 'X' in this context

I encountered an issue with a third-party library where the class structure changed. Initially, it was defined as: export class Foo { field: X[]; …. } In my code, I was working with this type: print(foo.field) After updating to a new version, the c ...

Programmatically setting focus in Ionic

In my Ionic and Angular component, I am attempting to programmatically set focus after the page has loaded. Here is the code: item.component.html: <ion-row> <ion-col col-5> <ion-item > <ion-label&g ...

How can I retrieve all element attributes in TypeScript using Protractor?

I came across this solution for fetching all attributes using protractor: Get all element attributes using protractor However, I am working with TypeScript and Angular 6 and struggling to implement the above method. This is what I have tried so far: im ...

Retrieving values from an array in a JSON response using Angular 4

How can I access the SubjectCode field in an array at a table using Angular 4? When trying to do so, I receive the error message: "[Error trying to diff '[object Object]'. Only arrays and iterables are allowed]". Here is the Json Response: { ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

Optimizing font loading with angular CLI

EDIT: AFAIK This is a unique question and not related to Webpack disable hashing of image name on output because: The webpack.config file is no longer editable in the latest versions of Angular CLI. I actually want to keep the hash on the fon ...

Deploy the Angular standalone component numerous times across a single page using Bootstrap

Edit After receiving input from Andrew, I have decided to adjust my strategy: Replacing survey-angular with the survey-angular-ui package Implementing a widget approach similar to the one outlined in this example Developing a single module that encompass ...

Show a reset button in an Angular 2 reactive form only when the form has unsaved changes

I am working with a reactive form and need to add a reset button that will return the form values to their initial state. The reset button should only be visible if the form is dirty. Here is the form definition: this.form = new FormGroup({ firstName: ...

How can Material UI React handle long strings in menu text wrapping for both mobile and desktop devices?

Is there a way to ensure that long strings in an MUI Select component do not exceed the width and get cut off on mobile devices? How can I add a text-wrap or similar feature? Desktop: https://i.sstatic.net/lo8zM.png Mobile: https://i.sstatic.net/8xoW6. ...

Issues arise with Google Cloud Builder for Angular when attempting to install Node SASS using the Cloud Builders Community image

Here are the steps I've taken so far: I have set up a Google Cloud Repository I created a Cloud Build Trigger and linked it to my GitHub account and repository, ensuring that the branch name matches exactly as ^staging$ Now, following instructions f ...

The event fails to propagate up to the parent component

I have a project structure set up as follows: https://i.stack.imgur.com/bvmK5.jpg The todo-form component triggers the created event and I am looking to handle this event in the todos component. todo-form.component.html: <form class="todo-form" ( ...

Unclear error message when implementing union types in TypeScript

Currently, I am attempting to define a union type for a value in Firestore: interface StringValue { stringValue: string; } interface BooleanValue { booleanValue: boolean; } type ValueType = StringValue | BooleanValue; var value: ValueType = { bo ...

Troubleshooting: Dealing with Cross-Origin Resource Sharing (CORS)

I'm facing an issue with my server.js files. One of them is located inside the backend folder, and when I run nodemon server.js on localhost:3000, everything runs smoothly. I start Angular by running ng serve inside the angular folder, and logging int ...