Tips for getting the array element in the 'field' attribute of the PrimeNG autoComplete

In my possession is a collection of JSON objects, here's an example:

 [
  {
    id: 'cont-609',
    contactMedium: [
      {
        characteristic: {
          emailAddress: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1b0a1c1b2f08020e0603410c0002">[email protected]</a>'
        }
      }
    ]
  }]

The task at hand is to retrieve the emailAddress (contactMedium[0].characteristic.emailAddress) from within PrimeNG autoComplete attribute 'field' in order to display a list of emails in a drop-down menu.

There will always be one element inside contactMedium

Provided below is my TypeScript code

import { Component, ViewChild } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { SelectItem } from 'primeng/api';
import { SelectItemGroup } from 'primeng/api';
import { FilterService } from 'primeng/api';
import { AutoComplete } from 'primeng/autocomplete';
import { CountryService } from './countryservice';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  providers: [CountryService, FilterService]
})
export class AppComponent {
  userDetails: any[];

  selectedUserDetails: any[];

  selectedValue: any;

  selectedUserDetail: any;

  constructor() {}

  ngOnInit() {
    this.userDetails = [
      {
        id: 'cont-609',
        contactMedium: [
          {
            characteristic: {
              emailAddress: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfbbaabcbb8fa8a2aea6a3e1aca0a2">[email protected]</a>'
            }
          }
        ]
      },
      {
        id: 'cont-610',
        contactMedium: [
          {
            characteristic: {
              emailAddress: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c78697f784c6b616d6560226f6361">[email protected]</a>'
            }
          }
        ]
      },
      {
        id: 'cont-611',
        contactMedium: [
          {
            characteristic: {
              emailAddress: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b9cddccacdf9ded4d8d0d597dad6d4">[email protected]</a>'
            }
          }
        ]
      },
      {
        id: 'cont-612',
        contactMedium: [
          {
            characteristic: {
              emailAddress: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b3c7d6c0c7f3d4ded2dadf9dd0dcde">[email protected]</a>'
            }
          }
        ]
      },
      {
        id: 'cont-614',
        contactMedium: [
          {
            characteristic: {
              emailAddress: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d6c7d1d6e2c5cfc3cbce8cc1cdcf">[email protected]</a>'
            }
          }
        ]
      }
    ];
  }

  filterUserDetails(event) {
    let filtered: any[] = [];

    for (let val of this.userDetails) {
      filtered.push(val);
    }
    this.selectedUserDetails = filtered;
  }

  getUserDetails(): Promise<any[]> {
    return Promise.resolve(this.userDetails);
  }

  chooseItem(event) {
    this.selectedUserDetail =
      event.contactMedium[0].characteristic.emailAddress;
  }
}

Displayed below is my HTML code

        <h5>Dropdown Testing</h5>
    <p>selectedUserDetail : {{selectedUserDetail}}</p>
    <p>TestVal : {{testVal}}</p>
    <p-autoComplete [(ngModel)]="selectedUserDetail" [suggestions]="selectedUserDetails"
      (completeMethod)="filterUserDetails($event)" [dropdown]="true" field="contactMedium">
      <!--<ng-template let-userDetails pTemplate=" item">
        <div>{{userDetails.contactMedium[0].characteristic.emailAddress}}</div>
      </ng-template> -->
    </p-autoComplete>

This section of the attribute is not functioning properly, field="contactMedium[0].characteristic.emailAddress" however if I use the non-array "id" property from the JSON, it works fine field="id" , but the aim is to showcase email addresses.

Feel free to explore the implementation via the link provided below:

https://stackblitz.com/edit/primeng-autocomplete-demo-dyihrs?file=src%2Fapp%2Fapp.component.html

Answer №1

UPDATE

Unfortunately, it is not feasible as primeng does not support fields within an array. An examination of the code in the autocomplete component and the function used for field resolution confirms this limitation.

---

The issue arises when trying to access an array within contactMedium:

contactMedium[0].characteristic.emailAddress

It seems that the documentation only supports objects without arrays.

AutoComplete functionality can be extended to work with objects by utilizing the field property to specify the displayed label for suggestions.

In case a workaround is needed, one could consider modifying the object to eliminate the array.

View this example which demonstrates that the usage of contactMedium as an array does not function correctly.

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 Angular subscription gets triggered multiple times

I am currently subscribed to this service: login(): void { if (!this.loginForm.valid) { return; } const { email, password } = this.loginForm.value; this.authService.login(email, password).subscribe((res) => { if (res.ok) ...

Angular now displays an unsupported Internet Explorer version message instead of showing a white screen

I am responsible for developing new features and maintaining an Angular application (version 8.3.4). Initially, we wanted the application to be compatible with all versions of Internet Explorer, but that turned out to be impractical. While the application ...

Creating a list of components for drag and drop with Angular CDK is a straightforward process that involves following

I am attempting to use Angular's CDK drag and drop functionality to create a list of components that can be rearranged. However, I am encountering an issue where the components are not being displayed correctly. In my App.component.ts file: impo ...

Establishing the starting value for Angular 2's reactive FormArray

I am having trouble setting the initial value for an angular 2 reactive form formArray object. Despite using a json object with multiple entries to set the form value, only the first entry is displayed and "form.value" also only shows the first entry. To ...

Having trouble with the Angular 2 router event not triggering on the initial try?

When navigating from one component to another, I want to access the URL of the previous route once the new route has been reached. In the constructor of the component being navigated to, I have included the code below. However, I am facing an issue where t ...

Having difficulty forming queries correctly using TypeScript, React, and GraphQL

Apologies for the potentially naive question, but I am new to working with GraphQL and React. I am attempting to create a component that contains a GraphQL query and incoming props. The props consist of a query that should be passed into the GraphQL query. ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

Guide to incorporating eslint with Next.js in a project that already has an eslint configuration

I recently created a new next.js project within my existing Node.js project, which already has an eslint config set up. Here's how the folder structure looks now: ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Tips to prevent elements from overlapping in Angular applications

I am facing an issue with my Angular-based app where I dynamically populate the page with table rows. There is an app-console element below the page that has a fixed position. Whenever I click the button to add a new row, it overlaps with the app-console. ...

Setting character limits when defining string variables in TypeScript

Upon reviewing the documentation, it appears that there is no straightforward method to perform type checking for the minimum and maximum length of a string data type. However, is there a possible way to define a string data type using custom types in ord ...

Receiving an unexpected value from the input attribute

Currently, I am facing a challenge in retrieving data from another component by using the selector in the HTML file of the parent component. Here is how I implemented it: <app-graphs [module]="module" hidden></app-graphs> In the chi ...

Understanding how types intersect in TypeScript

I'm currently diving into Type Relations in TypeScript. Can someone help explain what happens when we intersect the types represented by these two expressions: {a:number}[] & {b:string}[] Does this result in {a:number, b:string}[] ? Any clarificat ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

How to target a particular Textfield in React with its unique identifier

I'm working on a component that contains various Textfields and need to access specific IDs. For example, I want to target the textfield with the label 'Elevator amount'. I attempted the following code snippet but am unsure of how to correct ...

Issues arise when trying to implement Angular class and it does

I'm currently facing some challenges using classes in Angular to simplify my coding process. So far, I haven't been able to get it to work properly. Below is the code snippet I'm working with and the error message that pops up: import { Wiz ...

React-Bootstrap columns are not displaying in a side by side manner and are instead appearing on separate lines

I am currently integrating Bootstrap into my React project alongside Material UI components. Below is a sample of one of my components: import { styled } from "@mui/material/styles"; import Paper from "@mui/material/Paper"; import Cont ...

How can we efficiently load paginated data from a database while still implementing pagination using Angular Material?

I have a large table with more than 1000 entries that I want to display using a <mat-table></mat-table>. Since loading all the entries at once would be too much, I am looking to implement pagination and load only 20 entries per page. The chal ...

An issue occurred when attempting to create a collapsible/expandable button within an Angular Material Nested Tree

I am currently working on an Angular Material Nested tree and I'm facing an issue while trying to implement a button for expanding/collapsing. The error message I encounter is: ERROR TypeError: Cannot read property 'reduce' of undefined ...

There is a compatibility issue between the module and the engine "node" in this instance

Upon running the command npx create-react-app my-awesome-react-app --template typescript, I encountered the following yarn error: Error [email protected]: The engine "node" is incompatible with this module. Expected version "^6 || ^7 || ^8 || ^9 || ^10 || ...