Object autofill - Typescript utilizing Angular 5

I am working with an object called "features." Here is an example of the object:

[{"_id":"5af03d95c4c18d16255b5ac7","name":"Feature 1","description":"<p>Description</p>\n","neworchange":"new","releaseId":"5aead2d6b28715733166e59a","productId":"5aead2acb28715733166e599","__v":0},{"_id":"5af03db1c4c18d16255b5ac8","name":"Feature 2","description":"<p>Description 2</p>\n","neworchange":"change","releaseId":"5aead2d6b28715733166e59a","productId":"5aead2acb28715733166e599","__v":0}]

There is an input box that automatically populates with values from this object.

<input
    id="typeahead-focus"
    type="text"
    class="form-control"
    formControlName="relatedFeature"
    [ngbTypeahead]="search"
    (focus)="focus$.next($event.target.value)"
    (click)="click$.next($event.target.value)"
    #instance="ngbTypeahead"
    />

The input box displays the feature names, but when the form is submitted, I need to pass the ID instead.

The autofill code was obtained from this example:

import {NgbTypeahead} from '@ng-bootstrap/ng-bootstrap';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/merge';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
model:any;
angForm: FormGroup;
features:any;

@ViewChild('instance') instance: NgbTypeahead;
focus$ = new Subject<string>();
click$ = new Subject<string>();

constructor(//Code omitted) {
this.createForm();
}

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

createForm() {
this.angForm = this.fb.group({
name: ['', Validators.required ],
description: ['', Validators.required ],
relatedFeature: ['']
});
}

ngOnInit() {

}
getFeaturesByProduct() {
this.route.params.subscribe(params => {
this.featureservice.getFeaturesByProduct(params['productid']).subscribe(res => {
this.features = res;
});
});

Currently, the autofill box looks like this:

https://i.stack.imgur.com/pMYXU.png

However, I need to display the names of the objects inside the box.

Any help or alternative methods are appreciated. Thank you.

Answer №1

Here is a solution that might be helpful for the issue at hand.

An alternative approach is to utilize ng-template to create a customized template for displaying results and utilizing an object as a model.

I have put together a demonstration on stackblitz. Hopefully, this will offer assistance or guidance to you and others.

Sample HTML Code

<ng-template #rt let-r="result" let-t="term">
  {{ r.name}}
</ng-template>

<input
  id="typeahead-focus"
  type="text"
  class="form-control"
  [(ngModel)]="model"
  [ngbTypeahead]="search"
  (focus)="focus$.next($event.target.value)"
  (click)="click$.next($event.target.value)"
  #instance="ngbTypeahead"
  [inputFormatter]="formatter"
  [resultTemplate]="rt"
/>
<pre>Selected: {{ model | json }}</pre>

Sample TypeScript Code

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

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

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 onChange function in React is not behaving as I anticipated

Consider the following data structure for tables: an array of objects containing nested objects: [ { "1": { "1": "Item s ", "2": "Manufacturer ", "3" ...

Errors during TypeScript compilation in Twilio Functions

When I run npx tsc, I encounter the following errors: node_modules/@twilio-labs/serverless-runtime-types/types.d.ts:5:10 - error TS2305: Module '"twilio/lib/rest/Twilio"' does not export 'TwilioClientOptions'. 5 import { Twil ...

What is the best way to set up a variable in Typescript that will be assigned the value of an asynchronous request once it is completed?

As a newcomer to typescript, I encountered an issue that hadn't occurred in my previous project. It appears that declaring a variable before an API request inside a try-catch block leads to typescript errors when attempting to use this variable after ...

Ways to selectively apply colors to particular rows within an AntD table

I'm attempting to apply different colors to entire rows depending on certain data values from the table's data source. I know that we can utilize rowClassName, but I'm not entirely clear on its functionality. If anyone could provide exampl ...

Why is it necessary to import Material-modules individually for various custom modules in Angular?

Within my applications, I utilize multiple modules with some being implemented through lazy loading. A common practice I have noticed is that for the lazy-loaded modules, I must import MatButtonModule (along with other modules) into their respective custom ...

What separates the act of declaring a generic function from explicitly declaring a type for that very same generic function?

Here are two instances demonstrating the use of a generic function: function myGenericFunction<TFunc extends Function>(target:TFunc): string { return target.toString(); } Based on this response, this represents a declaration for a generic funct ...

Issue encountered while attempting to establish a connection between Angular App and asp.net core signalr hub

I have developed an ASP.NET Core 3.1 application that utilizes Microsoft.AspNetCore.SignalR 1.1.0 and Microsoft.Azure.SignalR libraries. In the Startup file, the SignalR setup is as follows: services.AddSignalR().AddAzureSignalR("Endpoint=https://xx ...

There seems to be an issue with the 'clr-icon' element; it is not recognized as a valid element

When I run this specific command: ng build --prod --base-href ./ An error message is displayed: ERROR in : 'clr-icon' is not a known element: 1. If 'clr-icon' is an Angular component, then verify that it is part of this module. 2. If ...

Having trouble changing file names in a Next.js 13 project

I've been facing an issue ever since Next.Js 13 updated the `pages` folder to a new `app` folder. Whenever I try to rename the default "Pages.tsx" file to something like "Home.tsx" or "Information.tsx", it breaks and shows a 404 Page error. The first ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Angular Material's <mat-select> tag allows for the inclusion of an <input> element within it

I am attempting to place an input element inside the mat-select tag of the Angular Material element. However, I am facing an issue where I cannot input any text into the input field inside the select element. Below is the code I am using to search for elem ...

Angular dynamic array binding binds to multiple elements rather than just one

In my code, I am working with an array object structured as follows: let myArray=[ { "id":"100", "child1":[ {"id":"xx","Array":[]}, {"id":"yy","Array":[]}, {"id":"zz","Array":[]} ] }, { "id":"200", "child1":[ {"id":"xx","Array ...

Navigating with the Angular router leads to an unexpected destination: "mat-radio-group-0=true"

I'm facing an issue with a close button in my HTML template that triggers a close() function in the component: HTML template: <div> <label id="radio-group-label">Please specify: </label> <mat-radio-grou ...

Execute the form validation and submission simultaneously

I am facing an issue with my form validation and submission process. When I click on the creer button, the form validation works fine but the submit function does not work. I don't see any errors in my console. I have tried using the onsubmit() method ...

What is the reason behind the ability to assign any single parameter function to the type `(val: never) => void` in TypeScript?

Take a look at the code snippet below interface Fn { (val: never): void } const fn1: Fn = () => {} const fn2: Fn = (val: number) => {} const fn3: Fn = (val: { canBeAnyThing: string }) => {} Despite the lack of errors, I find it puzzling. For ...

Guide for displaying information as a grid or table format using Angular 4

I am tasked with handling data from an external microservice that is not always in a standard format. The data is dynamic and can include table data, along with metadata information above the grid. My challenge is to render or identify the table data, disp ...

Angular project models

I'm exploring the Core/Shared/Feature design pattern for building large, scalable applications in Angular, and I find myself unsure about where models fit in. Is there a consensus on which module they belong in? I came across a post suggesting that ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

Combining two observables into one and returning it may cause Angular guards to malfunction

There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict ac ...

Warning in VSCODE: Use caution when using experimental decorators

I have been working on an Angular2-Typescript application and created the project using angular-cli with the command: ng new myApp However, I am facing a warning issue when creating a new component with the @Component tag. I have tried to resolve this p ...