ng2-select is experiencing difficulties when attempting to retrieve and process data from an API while also casting it within the initData

Issue with ng2-select and API Data Retrieval

I am encountering a problem while using ng2-select in my form. I am fetching data from an API and setting it into an array, but it is not functioning correctly. Below is the code snippet I am working with. When I hard code the data, everything works fine. However, when I dynamically retrieve the data from the API, it seems like the array is not being properly initialized. The response gets the data, but it is not being set to the array as expected.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {Observable} from 'rxjs/Observable';
import { AuthService } from '../../services/auth/auth.service';
import {SELECT_DIRECTIVES} from 'ng2-select';

@Component({
selector: 'users-edit',
templateUrl: '../../app/components/user/user-edit.html',
directives: [SELECT_DIRECTIVES]
})
export class UserEditComponent implements OnInit{
private isAdmin: Boolean = false;
private _data: Observable;
private fname: string;
private id: number;
private lname: string;
private email: string;
private _roles: Observable;
public roles: any = [];
public groups: any = ['Group 1', 'Group 2', 'Group 3', 'Group 4', 'Group 5'];
private initRoleData: Array[]=[]; 
private _disabledV: string = '0';
private disabled: boolean = false;


constructor(private router: Router,
    private userService: UserService,
    private route: ActivatedRoute,
    private authService: AuthService) {

    this.route.params.subscribe(params => {
        this.id = +params['id'];
    });
}

ngOnInit() {
    this.userService.getUser(this.id)
        .subscribe(data => {
            this.fname = data.FirstName;
            this.lname = data.LastName;
            this.email = data.Email;
        });
    this.userService.getUserRolesById(this.id)
        .subscribe(data => {
            data.forEach(role => {
                this.initRoleData.push(role.Name);             
            });
        });
    console.log(this.initRoleData);
    this.userService.getAllRoles()
        .subscribe(data => {
            data.forEach(role => {
                this.roles.push(role.Name);
            });
        });
    console.log(this.roles);
}
}

HTML Form Section

<div class="row margin-bottom-40" style="margin-top:50px;">
    <div class="col-md-12">
        <form id="sky-form4" class="sky-form" (ngSubmit)="Submit(userEdit)" #userEdit="ngForm">
            <header>Edit User Account</header>

            <fieldset>
                <section>
                    <label class="input">
                        <i class="icon-append fa fa-user"></i>
                        <input type="text" name="username" placeholder="First Name" required [value]="fname">
                        <b class="tooltip tooltip-bottom-right">Enter First Name</b>
                    </label>
                </section>

                <section>
                    <label class="input">
                        <i class="icon-append fa fa-user"></i>
                        <input type="text" name="username" placeholder="Last Name" [value]="lname">
                        <b class="tooltip tooltip-bottom-right">Enter Last Name</b>
                    </label>
                </section>

                <section>
                    <label class="input">
                        <i class="icon-append fa fa-envelope"></i>
                        <input type="email" name="email" placeholder="Email address" [value]="email">
                        <b class="tooltip tooltip-bottom-right">Enter Email Address</b>
                    </label>
                </section>

                <section>
                    <label>
                        Roles
                    </label>
                    <div>
                        <ng-select 
                                   [multiple]="true"
                                   [items]="roles"
                                   [disabled]="disabled"
                                   (data)="refreshValue($event)"
                                   (selected)="selected($event)"
                                   (removed)="removed($event)"
                                   placeholder="No roles assign">
                        </ng-select>
                    </div>
                </section>
                
                <!--<section>
                    <label>
                        Groups
                    </label>
                    <div>
                        <ng-select 
                                   [multiple]="true"
                                   [items]="groups"
                                   [disabled]="disabled"
                                   (data)="refreshValue($event)"
                                   (selected)="selected($event)"
                                   (removed)="removed($event)"
                                   placeholder="No groups assign">
                        </ng-select>
                    </div>
                </section>-->
            </fieldset>
            <footer>
                <button type="reset" class="btn-u">Cancel</button>
                <button type="submit" class="btn-u" [disabled]="!userEdit.form.valid">Save</button>
            </footer>
        </form>
    </div>

</div><!--/end row-->
 

Answer №1

Check out this github issue for more information on the problem at hand.

A workaround discovered by jkwiz involves enclosing your select element within an *ngIf div to delay its creation until after the data query is complete:

    ...
    ...
           <section>
                <label>
                    Roles
                </label>
                <div *ngIf="roles.length > 0">
                    <ng-select 
                               [multiple]="true"
                               [items]="roles"
                               [disabled]="disabled"
                               (data)="refreshValue($event)"
                               (selected)="selected($event)"
                               (removed)="removed($event)"
                               placeholder="No roles assign">
                    </ng-select>
                </div>
            </section>
    ...
    ...

One drawback of this solution is the inability to dynamically add rows to your select, a known issue with ng2-select that may not be addressed immediately given the age of the problem despite its critical nature.

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

Ways to resolve the issue of the missing property 'ganttContainer' on the 'Gantt' type

I encountered an issue while trying to utilize the Gantt chart feature from the Dhtmlx library in TypeScript. The problem seems to stem from an error during the initialization of gantt. How can I go about resolving this? Below is the relevant code snippet: ...

Dealing with Nested Body Payload in PATCH Requests with Constructor in DTOs in NestJS

Within my NestJS environment, I have constructed a DTO object as follows: export class Protocol { public enabled?: boolean; public allowed?: boolean; constructor(enabled: boolean, allowed: boolean) { // With a necessary constructor this.enabled = ...

Tips for effectively generating a JSON object array in Typescript

Currently, I'm attempting to construct an array of JSON objects using TypeScript. Here is my current method: const queryMutations: any = _.uniq(_.map(mutationData.result, function (mutation: Mutation) { if (mutation && mutation.gene) { co ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

Can data be transmitted in Angular without using a selector?

I am facing a challenge in sending data from a child component to its parent. The parent component's HTML code does not utilize the child's selector, as it is within a dialog of Angular Material and only uses "MatDialogRef" and "dialog.open()". T ...

Sharing an array with a child component using the @Input decorator

I am attempting to send an array to a child component. The array is created within the subscribe method of the onInit lifecycle hook in the parent component. Parent component: import { Component, OnInit } from '@angular/core'; @Component({ s ...

What is the importance of using getters for functions involving Moment.js in vueJS and typescript?

weekOfMonth() calculates the current month and week within that month. <template> <h3>{{ weekOfMonth }}</h3> </template> <script lang="ts"> export default class HomeView extends Vue { const moment = require(& ...

TS2367: Given any input, this condition will consistently evaluate to 'false'

I'm struggling to understand why the compiler is not including null as a possible type for arg, or perhaps I am misinterpreting the error message. static vetStringNullable(arg:any): string|null { if (typeof arg === 'string') { ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...

Setting up the Angular 2 environment with angular-cli: A step-by-step guide

Attempting to configure environment settings using angular-cli following the guide at https://github.com/angular/angular-cli#build-targets-and-environment-files However, even after running "ng build --prod -aot", the output pages continue to display conte ...

Password validations are a key feature of reactive forms

Currently, the sign-up button only becomes enabled if the signup form is valid. However, I am facing an issue where the button is getting enabled even when the password and confirm password fields do not match. I suspect there might be a problem with my i ...

The fillFormValues function is not functioning properly within the mat-select element

I need help filling a form value by id. This function successfully retrieves the value: fillFormValues(expenseCategory: ExpenseCategory): void { console.log('response', expenseCategory.parent_category) this.aa= expenseCategory.parent_c ...

What could be causing me to consistently receive a 0 value despite my collection having content stored within it?

How can I retrieve the value of dropVolume and use it in another method after executing my getAllDropsVolumePerDate(date) function? Each time I try to access dropVolume, it returns a value of 0. dropVolume = 0; getAllDropsVolumePerDate(date: string) { ...

When Android build APK is released, HTTP requests fail, yet they work seamlessly during debugging

While debugging, all API calls function correctly. However, when creating a build apk file, the requests are not being called in the build apk. Despite having an SSL certificate on the server, the request still fails to go through. ...

Angular 7 and its scrolling div

Currently, I am working on implementing a straightforward drag and drop feature. When dragging an item, my goal is to scroll the containing div by a specified amount in either direction. To achieve this, I am utilizing Angular Material's CDK drag an ...

How to create Angular applications that are independent of their environment?

I am in the process of updating my codebase to ensure that the variables used will function correctly regardless of the environment. Angular's angular.json offers the option to include environment-specific configurations. I am also interested in findi ...

What is the most effective method for dividing a string in TypeScript?

Here is the scenario: receiving a string input that looks like Input text: string = "today lunch 200 #hotelname" Output subject: "today lunch" price: 200 tag: #hotelname My initial solution looks like this: text: string = "today lunch 200 #hotelname" ...

Opt for Readme display over index.html

I'm just starting out and I have a question about Github: Is there a way to build a page using the index.html file within a folder instead of the readme file? I've successfully built many pages where the index file is not located in a folder. Ho ...

Despite using Enzyme to locate a component again, the expected prop value is still not being returned

Two components are involved here - a modal and a button that is meant to open the modal by setting its isOpen prop to true. The initial state of the modal is set to false, but when the button is clicked, it should change to true. While everything works fi ...

Tips for saving the generated POST request ID for future use in another function

I am facing a challenge where I want to use the ID of a newly created Order as the OrderId for an OrderLine that needs to be created immediately after. After creating the Order, if I log the orderId INSIDE THE SUBSCRIBE METHOD, it shows the correct value. ...