Angular 6 presents a challenge in rendering data within the multi select drop down feature

I am currently utilizing a multi-select library called ng-multiselect-dropdown in my Angular v6 project.

Unfortunately, when I try to display my list using the multiSelect feature, the drop-down shows a message saying "No data available".

I discovered that if I hardcode my response, the list populates correctly. However, I am puzzled as to why my dynamic response is not working properly.

this.members = [
  {
    "item_id": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f2a2c3a2d6e1f38323e3633713c3032">[email protected]</a>",
    "item_text": " User 1"
  },
  {
    "item_id": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f4f2e4f3b3c1e6ece0e8edafe2eeec">[email protected]</a>",
    "item_text": " User 2"
  }]

HTML

<ng-multiselect-dropdown [placeholder]="'Select Member Names'" [data]="members"
                [(ngModel)]="selectedMembers" [settings]="dropdownSettings" (onSelect)="onItemSelect($event)"
                (onDeSelect)="onItemDeSelect($event)">
</ng-multiselect-dropdown>

TS

export class IndividualDashboardComponent implements OnInit {


  selectedMembers: Array<any> = [];
  getIndividualMemberResponse: any;
  statusCode: number;
  members = [];
  dropdownSettings = {};
  constructor(private route: ActivatedRoute, private toastMessageService: NotificationService, private http: HttpService) { }


  ngOnInit(): void {
    this.fetchMembers();

    this.dropdownSettings = {
      singleSelection: false,
      idField: 'item_id',
      textField: 'item_text',
      selectAllText: 'Select All',
      unSelectAllText: 'UnSelect All',
      itemsShowLimit: 4,
      allowSearchFilter: true
    };

  }
  fetchMembers() {
    let teamName: String = "All";
    let urlString: any = environment.ALL_TEAM_MEMBERS + teamName;
    this.http.getRequest(urlString, null, null)
      .subscribe((data) => {
        (<Array<String>>data).forEach(member => {
          this.members.push({ item_id: member, item_text: member });
        });
        console.log(JSON.stringify(this.members))
      },
        (error: Response) => {
          this.getIndividualMemberResponse = error;
          this.statusCode = this.getIndividualMemberResponse.status;
          this.toastMessageService.errorMessageToast(this.statusCode);
        });
  }


  onItemSelect(item: any) {
    if (this.selectedMembers.length === 0) {
      $('#submitButton').prop('disabled', true);
    } else {
      $('#submitButton').prop('disabled', false);
    }
  }
  onItemDeSelect(item: any) {
    if (this.selectedMembers.length === 0) {
      $('#submitButton').prop('disabled', true);
    } else {
      $('#submitButton').prop('disabled', false);
    }
  }
}

EDITED

I made a change to my method but it did not fix the issue.

  fetchMembers() {
    let urlString: any = environment.ALL_TEAM_MEMBERS + 'All';
    this.http.getRequest(urlString, null, null)
      .subscribe((data) => {
        this.members = 
         (<Array<String>>data).map(member => ({ item_id: member, item_text: member }));
        console.log(JSON.stringify(this.members))
      });
  }

Answer №1

UPDATE:

An important issue arises from the requirement that the select component expects a value of type

{item_id:number, item_text:string}[]
for the data property, but it seems that you are incorrectly mapping the data in the subscribe callback.

Please note that you are adding objects to the members array, and these objects have properties item_id and item_text corresponding to the elements in the data array being iterated in the subscribe callback.

Instead of doing this:

this.members.push({ item_id: member, item_text: member });

You should do this:

this.members.push({ item_id: member.item_id, item_text: member.item_text });

To avoid such issues, it is advisable to explicitly declare the types of your instance members. For instance:

interface SelectItem {
  item_id: number;
  item_text: string;
}

export class IndividualDashboardComponent implements OnInit {
   ...
   members: SelectItem[] = [];
   ...

   getMembers(){
     ...
     this.http.getRequest(urlString, null, null)
      .subscribe((data: SelectItem[]) => this.members = data);
     ...
   }
}

ORIGINAL:

The problem likely lies in the fact that you modify the members array. The select component uses onPush change detection, which supports this assumption.

Try replacing the mutation of the members array with assigning a new value to it instead. You can achieve this by refactoring your code to use map instead of forEach inside the subscribe callback, like so:

this.members = data

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

Issue: Unable to locate the name 'ContactField' in Ionic 2

While attempting to use Ionic2 to save a contact, an error occurs when running the app through the command line. The cordova-plugin-contacts has been properly installed. Below is the code snippet: import { Component } from '@angular/core'; impo ...

Link a template to a formly field when clicking on another field within an Angular formly form

Recently, I have been utilizing a Formly form that includes a section for displaying dynamic HTML content. Within this form, I am using the template field to initialize some HTML content when the page loads. However, I have encountered an issue where chang ...

Incorporate a background image into mat-dialog

I've been struggling to set a background image on my mat-dialog, but for some reason it's not showing up at all. I attempted using a panelClass as well, but still no luck. .custom-panel .mat-dialog-container { background-image: url("../. ...

ng2 - Comparing DevExtreme and Telerik Kendo UI

Our team is embarking on a new software project utilizing Angular2, typescript, and HTML5. We are considering two options for UI components: - DevExtreme - Telerik Kendo UI Which of these would be the best choice in your opinion? Thank you! ...

The predicament with arranging arrays

I'm working with an array that looks like this: [ { "TaskID": 303, "TaskName": "Test1", "TaskType": "Internal", "Status": "Processing", "IsApproved": false, "RowNumber": 1 }, { "TaskID": 304, ...

Is there a way to execute a javascript function that is located outside of my Angular application without having to import it?

I need to be able to trigger a JavaScript function that is located outside of my Angular app when a button is clicked. Unfortunately, it seems that importing the JavaScript directly into my Angular app isn't feasible for this task. The platform I am ...

Angular displays RouterLink as regular text

I am currently learning Angular and encountering an issue with the routerLink attribute in my <a> tag. When I add the routerLink, it changes to text and becomes unclickable. Can anyone help me identify what is causing this problem? Here is a snippet ...

What is the best way to remove all validators from a different component in Angular 7 using reactive forms?

I need to find a way to clear all validation in a form group on a sibling component when a boolean value is selected on another component within the same application. Is there a solution for achieving this? We have implemented a method in our application ...

Troubleshooting: Issues with MagicSuggest's dependent multiple dropdown functionality

Currently implementing MagicSuggest for a custom dropdown feature with two dropdowns: category and subcategory. The goal is to have the subcategories populate based on the selected category. However, after selecting a category and then a subcategory, if ...

Using Angular to Apply a Custom Validation Condition on a FormGroup Nested Within Another FormGroup

I am facing an issue with my form validation logic. I have a set of checkboxes that need to be validated only when a specific value is selected from a dropdown. The current validator checks the checkboxes regardless of the dropdown value. Here's the c ...

Unleashing the power of RXJS: Leveraging IntervalObservable coupled with the

I recently incorporated HTTP pooling into my Angular application using IntervalObservable and startWith for immediate activation. I'm curious to know if IntervalObservable waits for the initial/previous call to finish streaming data. Also, is there a ...

Encountered CORS error when attempting to access the dynamic menu API after logging

Currently, I am working on an Angular 6 and Codeigniter project. In this project, the slider and navigation menu bar are being fetched dynamically through a REST API. Everything runs smoothly until the login process, where a CORS error is encountered. htt ...

How to instantiate an object in Angular 4 without any parameters

Currently, I am still getting the hang of Angular 4 Framework. I encountered a problem in creating an object within a component and initializing it as a new instance of a class. Despite importing the class into the component.ts file, I keep receiving an er ...

What exactly is the concept behind the Strategy OnPush?

I am a beginner in the world of Angular2 with TypeScript. As I delve into my project, one concept that continues to elude me is the purpose of OnPush: changeDetection : ChangeDetectionStrategy.OnPush Despite my dedicated efforts in researching this top ...

Angular: Creating an instance of a class with StaticProvider passed as a parameter

Having trouble instantiating a class with a StaticProvider. Here's the code snippet: main.ts export function createProvider() { // some implementation return result; // result is a string } const providers = [ { provide: 'TEST' ...

Sharing data between two components in Angular 7

The Address object values are not being retrieved as expected when requesting from the credit card component to a function called getAddress() in a config service that holds the value. Instead of the updated values, I am getting the initial values. Below i ...

Discover the method of sending individual row data to a component using *ngFor in Angular 4

I need assistance with Angular as I am not very experienced in it. Here is the HTML code that I have: <tbody> <tr *ngFor="let data of employeeFilterLists"> <td>{{data.Code}}</td> <td (clic ...

Instructions for disabling editing for a specific cell within an inline editable row in primeNG

I am currently using PrimeNG DataTable with Angular, where the rows are editable as shown in the example in the documentation: https://www.primefaces.org/primeng/#/table/edit. However, I am facing an issue where I want to exclude one cell from being editab ...

Transmit information from an Angular application to a Spring Boot server using a POST request

Attempting to send JSON data from a frontend Angular project to a Spring Boot backend for the first time. Limited experience with both technologies and unsure if the HTTP POST method in Angular is incorrect, or if the backend isn't receiving the expec ...

Developing in Angular 2: Enhancing JSON data before passing it to the template

After receiving data from a JSON source, I have the following: { "name": "Leonardo", "weapon": "sword" }, { "name": "Donatello", "weapon": "stick" }, { "name": "Michelangelo", "weapon": "nunchucks" }, { "name": "Raphael", " ...