The value I'm receiving for my list of objects is not accurate

Currently, I'm experimenting with implementing TYPEHEAD for user input using the ng-bootstrap library. The goal is to display a list of objects (similar to a select option without a dropdown box):

HTML

<input type="search"
       #instance="ngbTypeahead"
       placeholder="Search"
       aria-label="Search"
       [(ngModel)]="model"
       [ngbTypeahead]="search"
       [resultTemplate]="rt"
       [inputFormatter]="formatter"
       (focus)="focus$.next($event.target.value)"
       (click)="click$.next($event.target.value)"
>

As I type the name of an object, I am currently receiving 'empty value' displayed seven times (representing all the desired objects) until I actually select one, in which case the selected value appears correctly in the input field (though not in the select box).

TS

  search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      merge(this.focus$),
      merge(this.click$.pipe(filter(() => !this.instance.isPopupOpen()))),
      map(term => (term === '' ? this.productList
        : this.productList.filter(v => v.name_product.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10))
    );

   formatter = (x: {name_product: string}) => x.name_product;

    searchUrl(url){
      if(url){
        window.open(url,'_blank');
      }
    }

JSON

  productList =
  [ 
    {
        id_product:1,
        name_product: 'Laptop Dell'
    },
    {
        id_product:2,
        name_product: 'Laptop HP'
    },
    {
        id_product:3,
        name_product: 'G-Shock Casio'
    },
    {
        id_product:4,
        name_product: 'Casio LR-T CALC'
    },
    {
        id_product:5,
        name_product: 'LG G3 Stylus'
    },
    {
        id_product:6,
        name_product: 'DYMO 450 Turbo'
    },
    {
        id_product:7,
        name_product: 'Brother QL 700'
    }
  ];

My objective is to display product names (name_product), while still obtaining the corresponding ID (id_product) into my [(ngModel)]="model". How can I resolve this issue?"

Check out my stackblitz here to further understand this bug.

Answer №1

Your issue can be found in the HTML code

I will now demonstrate how you can retrieve the id

https://example.com/edit/angular-abc123

<label for="typeahead-basic">Search :</label>

<ng-template #rt let-r="result" let-t="term">
  <div (click)='getId(r.id_product)'>{{r.name_product}}</div>
</ng-template>

<input id="typeahead-template" type="text" [(ngModel)]="model" [ngbTypeahead]="search" [resultTemplate]="rt"
[inputFormatter]="formatter" />

<button class="btn btn-outline-success my-2 my-sm-0" type="submit" (click)="searchUrl(model.url)">Search</button>

<pre>Model: {{ model | json }}</pre>

Id: {{id}}

TS Code

 getId(id: number) {
    this.id = id;
}

Answer №2

Modify this specific line within the <ng-template>

<ng-template #rt let-r="result" let-t="term">
  <ngb-highlight [result]="r.name_product" [term]="t"></ngb-highlight> 
   //alternatively, you can display the item using {{r.name_product}}
</ng-template>

See Demo

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

Rendering HTML content in a preformatted <code> tag using Electron

Recently, a brand new electron/angular application was built with the code snippet running in main.ts: win.loadURL(url.format({ pathname: path.join(__dirname, 'dist/index.html'), protocol: 'file:', slashes: true })); After launc ...

Troubleshooting issues when integrating three.js GLTFLoader() with TypeScript due to conflicts with zimjs

Successfully loading a model using three.js GLTFLoader() with TypeScript in a nuxt.js application: this.mGLTFLoader = new (<any>THREE).GLTFLoader(); this.mGLTFLoader.load(pPath, (gltf) => this.onLoad(gltf), (xhr) => this.onProgress(xhr), (e) = ...

An unexpected stats.js error occurred while attempting to apply custom styles to the map in AngularGoogleMaps,

My experience with Angular Google Maps has been mostly positive, except for one issue that I have encountered. When attempting to add styles to the map using the styles input attribute, I encounter an error: js?v=quarterly&callback=agmLazyMapsAPILoad ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

Ultimate combo: React, TypeScript, and Vite for seamless imports!

Problem The issue I'm facing is related to my React app built with the command yarn create vite. I tried to switch to using absolute imports instead of "../../.." in my files, but unfortunately it doesn't seem to work in my React + Vi ...

The 'status' attribute is not found within the 'User' data type

Currently, I am invested in a personal project using Angular 6 for the client side and Laravel 5.6 for my API. Despite successful testing of the API endpoints with Postman, I find myself struggling to comprehend the behavior of my auth service. To provide ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Utilizing svgr in NextJS with TypeScript and Webpack

I have a collection of separate svg files that I want to load in React and use as React components. Here is an example of how I am trying to do this: import SampleIcon from '@/components/editor/icons/add-column-after.svg'; <SampleIcon classNam ...

Infragistics: A guide to displaying numerous ignite Snackbar instances with unique identifiers

I am trying to display multiple Snackbars on my Angular website. I'm utilizing Ignite UI for Angular and incorporating the Snackbar feature from Ignite. <igx-snackbar id="snackbar1" [displayTime]="displayTime"> <div [cla ...

The npm package has been successfully installed, but VS Code is having trouble locating it

Currently, I am in the process of developing a simple npm package known as type-exception using TypeScript. After successful test runs and publication on NPM, I have been able to install it into another project (project B). However, upon importing it as a ...

How to Hide Parent Items in Angular 2 Using *ngFor

I am dealing with a data structure where each parent has multiple child items. I am trying to hide duplicate parent items, but accidentally ended up hiding all duplicated records instead. I followed a tutorial, but now I need help fixing this issue. I only ...

Rxjs: handling arrays of observables by processing them in batches

I am facing a scenario where I have an array of observables. Let's say: const responses$: Observable<Response>[] = [ this.service.get(1), this.service.get(2), this.service.get(3), this.service.get(4) ]; My goal is to process ...

Showing information from a JSON dataset of users once a specific User ID has been chosen

My task involves displaying user data from an array and then showing the details of the selected user. I attempted to achieve this with the following code: users = USERS; // contains data selectedUser: User; constructor() { } ngOnInit() { } onSelect(i ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

What is the subclass of all object literal types in TypeScript?

With the `strictFunctionTypes` setting turned on, function parameters are checked contravariantly. interface Func<T> { (p: T): unknown } declare let b: Func<{p1: string}> declare let c: Func<{p2: number}> declare let d: Func<{p3: nu ...

Managing Angular Universal in a production environment can be a challenging task

I am currently working on a project that utilizes the MEAN stack. Front-end: Angular 6.*. Backend: ExpressJs and Mongodb. During development, Angular runs on port 4200, while ExpressJs runs on port 3000. For production, I build Angular and serve it as ...

What is the best way to set up the parser and plugins using ESLint's updated flat configuration?

How can ESLint be configured using the new "flat config" system (specifically with the eslint.config.js file) to work seamlessly with both @typescript-eslint/eslint-plugin and /parser? I have been struggling to make ESLint's new configuration system ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...

Receive a notification when the div element stops scrolling

I am attempting to replicate Android's expandable toolbar within an Angular component. My HTML code appears as follows: <div (scroll)="someScroll($event)"> <div class="toolbar"></div> <div class="body"></div> </d ...

The module 'NgAutoCompleteModule' was declared unexpectedly by the 'AppModule'. To fix this issue, make sure to add a @Pipe/@Directive/@Component annotation

Currently, I am attempting to integrate an autocomplete feature into my Angular 2/4+ project. Despite trying various libraries, none of them seem to be working correctly. Each one presents me with a similar error message: Unexpected module 'NgAutoCom ...