question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

ng2-select not working when I get data from api and cast it in initData

See original GitHub issue

I use two ng2-select in one form. I retrieve data from api and set into the array but it not working correctly. bellow is my code. when I hard code it is working fine.

.Ts

`[import { Component, OnInit } from ‘@angular/core’; import { Router, ActivatedRoute } from ‘@angular/router’; import { InviteUserComponent } from ‘./invite-user.component’; import { UserListComponent } from ‘./user-list.component’; import { SimpleNotificationsComponent } from ‘angular2-notifications’; import { AuthorizeUserDirective } from ‘…/…/directives/authorize-user.directive’; import { UserService} from ‘…/…/services/user.service’; 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<any[]>; private fname: string; private id: number; private lname: string; private email: string; private _roles: Observable<any[]>; public roles: any = []; public groups: any = [‘Group 1’, ‘Group 2’, ‘Group 3’, ‘Group 4’, ‘Group 5’]; private initRoleData: Array<any>[]=[]; private _disabledV: string = ‘0’; private disabled: boolean = false; private get disabledV(): string { return this._disabledV; }

private set disabledV(value: string) {
    this._disabledV = value;
    this.disabled = this._disabledV === '1';
}

public selected(value: any): void {
    console.log('Selected value is: ', value);
}

public removed(value: any): void {
    console.log('Removed value is: ', value);
}

public refreshValue(value: any): void {
    this.initRoleData = value;
}


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

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

private isCurrentUserAdmin() {
    this.userService.isCurrentUserAdmin(this.authService.getUserName())
        .subscribe(data => {
            this.isAdmin = Boolean(data);
        },
        error => {
            console.log("error while retriving admin");
            console.log(error);
            this.userService.handleError(error);
        });
}

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);
}



Submit(form: any)
{
    alert(form);

}

}](url)`

Html

` <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 [initData]="initRolesData"
                               [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>
    <!-- End Reg-Form -->
</div>`

Issue Analytics

  • State:open
  • Created 7 years ago
  • Reactions:3
  • Comments:11 (2 by maintainers)

github_iconTop GitHub Comments

12reactions
DanielKucalcommented, Oct 23, 2016

@AJMalik007 @monica11 I made it working with asynchronous data. Here are the steps:

  1. We need a template variable on our select: <ng-select #select></ng-select>
  2. Then import it into our Component class: @ViewChild('select') select;
  3. Update #select.items after you get the data:
ngOnInit(){
    this.someService.getAsyncData().subscribe(response => {
        this.select.items = response.data; // and update our select items
    });
}

Hope it helps you too 😃

1reaction
optimistexcommented, Feb 4, 2018

Hi. It was fixed in that fork: https://github.com/optimistex/ngx-select-ex

Read more comments on GitHub >

github_iconTop Results From Across the Web

ng2-select not working when I get data from api and cast it in ...
I use ng2-select in the form. I retrieve data from api and set into the array but it not working correctly. bellow is...
Read more >
Get data from a server - Angular
This tutorial sample mimics communication with a remote data server by using the In-memory Web API module. After installing the module, the application ......
Read more >
Angular Tutorial - 21 - Fetch Data Using HTTP - YouTube
2.3 HTTP Post Request with fetch () - Working with Data and APIs in ... Read JSON Data From API Using HttpClient |...
Read more >
How to Fetch Data From an API Using Angular - YouTube
Step by Step procedure here:https://www.munonye.com/how-to-create-amazing-ui-with-angular-material-bootstrap-and-font-awesome/Build the REST ...
Read more >
AngularJS | fetch data from API using HttpClient
The following steps are to be followed to reach the goal of problem. Step 1: Create the necessary component and application. Step 2:...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found