'selectedOptions is not updating on MatselectionList with ngModel

I have MatSelectionList with different Classes. First time when I select classes it will associate student into this classes.

This is working fine, but the problem is when I go to dialog again and select the student who already selected classes then checkbox with existing classes are not checked.

I am pushing associated classes id into selectedOptions. selectedOptions contains the Value but it is not updating Ui.

HTML contents

<mat-selection-list [(ngModel)]="selectedOptions" ngDefaultControl>
  <mat-list-option *ngFor="let class of Classes" [value]="class.class_id">
    {{class.ClassName}}
  </mat-list-option>
</mat-selection-list>

Component contents

@Component(...)
export class MyComponent { 
  
  selectedOptions: string[] = [];

  constructor(private service:StudentService){
    this.service.getStudentElement().subscribe((result)=> {
      this.selectedStudents.forEach((student) => {
        this.filteredStudents = result.filter(studentElement => {
          return studentElement.student == student.uid;
        });
      this.associatedClassForSelectedStudents(this.filteredStudents);
    })
  })

  associatedClassForSelectedStudents(selectedStudents: any){
    selectedStudents.forEach(element=> {
      if(element.class){
        this.selectedOptions.push(element.class)
      }
    })
  }

}

Value emitted by this.service.getStudentElement() subscriber:

[
  {
    student: "261a134847d-e814379eaea6"
    uid: "9dd97ede-8943-b8f471317d14"
    class: "11111111-ee9d-ed1401907fa9"
   }
]

Can anyone tell me what am i doing wrong?

Thank you



Solution 1:[1]

The this.selectedOptions.push(element.class) it's not changing the reference to the selectedOptions and that's why it is not seen as a change and the selected classes are not updated.

You can try to use concat method that would create a new array:

this.selectedOptions = this.selectedOptions.concat(element.class)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cristina Darie