Reputation: 15598
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?
Upvotes: 1
Views: 542
Reputation: 1605
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
};
});
});
}
Upvotes: 4