1

I have an add group module on which there is user list for which I am using angular2-select for multiple selections. The add group page open on click of a button. Here is the code

<ng-select [options]="users" [multiple]="true" [(ngModel)]="group.selectedUsers" placeholder="select users" name="users"></ng-select>

And I am filling with this API response data

ngOnInit() {
   this.userService.getAllUsers()
       .subscribe(data => {
            data.forEach(element => {
                this.users.push({ value: element.id, label: element.firstName});
            });
        })
}

Now the first time I open the add group page the user list is empty. The user list is filled after I open it the second time. Am I missing something?

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189

1 Answers1

4

I guess that the problem is that your this.users remains the same object, so angular will not detect a change if you push items to it. Therefore the component will not be updated and your options will not show up.

To get this to work you should let this.users point to a new Array:

ngOnInit() {
    this.userService.getAllUsers().subscribe((data) => {
        this.users = data.map((element) => {
            return {
                value: element.id,
                label: element.firstName
            };
        });
    });
}
Bastiaan van den Berg
  • 1,585
  • 1
  • 14
  • 20
  • now this is happening with some other variable. let selectedUserIds =this.group.memberList.nameId.map((member: any) => { return member.id }); this.selectedUsers = selectedUserIds; can you solve this? – Sunil Garg Mar 14 '17 at 11:55
  • @SunilGarg What is happening exactly? This seems to be about setting the value instead of the options. In that case make sure that selectedUsers is a list of strings (Array). – Bastiaan van den Berg Mar 25 '17 at 07:22