How to pre-select data to mat-selection-list from array

Viewed 1988

I am getting string like this, 55,118,122,126,116,58,125,119,132 from API. These are the ids. I have a angular mat-selection-list. I want to initially select these value. So, basically i want to update existing data and send it to again.

this is my Mat selection list.

 <mat-selection-list #yuvakslist  [(ngModel)]="preselectedOptions" 
(selectionChange)="onChangeYuvak()">
<mat-list-option *ngFor="let yuvak of yuvaks" class="mt-1" [value]="yuvak.user_id">
          <nb-user name="{{yuvak.cnt_first_name + ' ' + 
 yuvak.cnt_last_name}}" size="large" title="{{yuvak.cnt_mobile_no}}"
          picture="{{thumbnailImg}}{{yuvak.profile_picture}}">
          </nb-user>
        </mat-list-option>
      </mat-selection-list>

i tried assigning all the ids i receive from API to array like this.

const preselectedOptions: Number[] = data.data.present_contact;

i want to pre-select those values onto mat-selection-list. So, i can update form.

1 Answers

Instead of ngModel its better to use angular reactive forms to accomplish this.

Here is an example

app.component.html

<mat-form-field>
    <mat-select placeholder="Users" [formControl]="userForm" multiple>
        <mat-option *ngFor="let user of userList" [value]="user">
            {{user.name}}
        </mat-option>
    </mat-select>
</mat-form-field>

app.component.ts

import {Component} from '@angular/core';
import {FormControl} from '@angular/forms';

@Component({
    selector: 'app',
    templateUrl: 'app.component.html'
})
export class AppComponent {
    userList: any[] = [
        { name: 'Robin', id: 1 }, 
        { name: 'Pandey', id: 2 }
    ];
    userForm: FormControl;

    constructor() {
        this.userForm = new FormControl([this.userList[0]]);
    }
}
Related