2 Way data binding not working in ng-select Angular 6

Gopikrishn Imadabathuni picture Gopikrishn Imadabathuni · Jul 25, 2018 · Viewed 7.4k times · Source

I am using ng-select in my application.

My component class is

export class ExampleComponent {
     selectedCoursesList: Course[] = [];
     courseList: any[] = [];

     removeCourse( course: Course) {
         this.selectedCoursesList.forEach((item, index) => { 
          if (item === course) { 
                this.selectedCoursesList.splice(index, 1);          
          }
        });
    }
 }

and my html is

     <ng-select  placeholder="Choose course" [multiple]="true" 
        (ngModelChange)="updatecourse($event);" 
        [(ngModel)]="selectedCoursesList">
        <ng-option *ngFor="let course of courseList" [value]="course" >
                    {‌{course.name}} 
        </ng-option>
     </ng-select>

Here I want to achieve 2 things

  1. Un-selecting particular selected values of ng-select
  2. 2 way Data binding

Can any one tell me what I did wrong?

Thank You

Answer

Gopikrishn Imadabathuni picture Gopikrishn Imadabathuni · Jul 26, 2018

I achieved this by adding [formControl]="courses" in my

     <ng-select  [formControl]="courses" placeholder="Choose course" [multiple]="true" 
         [(ngModel)]="selectedCoursesList">
            <ng-option *ngFor="let course of courseList" [value]="course" >
                {‌{course.name}} 
            </ng-option>
      </ng-select>

and in my removeCourse method I added

this.courses.setValue(this.selectedWinaryList);

 export class ExampleComponent {
    selectedCoursesList: Course[] = [];
    courseList: any[] = [];
    courses= new FormControl();
    removeCourse( course: Course) {
         this.selectedCoursesList.forEach((item, index) => { 
             if (item === course) { 
                 this.selectedCoursesList.splice(index, 1);          
             }
         });
         this.courses.setValue(this.selectedWinaryList);
     }
 }

when I remove course from the array it automatically un-selecting that course from the select list.