0
votes

i am populating select list with Webapi and Service. So when i am going to update a record than the mat multiple select list not pre selecting the list items of user that he already select i am using setValue function for pre selection of list items.i hope you understand my question

Angular Code

<mat-form-field class="example-full-width">
    <mat-select placeholder="Select department(s)" formControlName="DepartmentName" multiple>   
      <mat-option *ngFor="let department of departmentList" [value]="department">{{department.departmentName}}</mat-option>
    </mat-select>
</mat-form-field>


ngOnInit() {
    this.service.getDepartList().subscribe(
        data =>
        {
            this.departmentList = data; // Department list that,s  actual list from api call
            //0: { departmentID: 1, departmentName: "Sales" }
            //1: { departmentID: 2, departmentName: "Marketing" }
            //2: { departmentID: 3, departmentName: "Management" }
            //3: { departmentID: 4, departmentName: "Human Resource" }
            //4: { departmentID: 5, departmentName: "Electrical" }
            //5: { departmentID: 6, departmentName: "Machenical" }
            //6: { departmentID: 7, departmentName: "Production" }
            //7: { departmentID: 9, departmentName: "Data Sciences" }
            this.router.queryParams.subscribe(data => { this.userId = data.userId })
            if (this.userId > 0) {
                debugger;
                this.service.getSingleUser(this.userId).subscribe( 
                    response => {
                        this.preSelectDep = response.departmentName; //data shown below i am receiving for here is list items that i want pre select on update from api call 
                        //0: { departmentID: 4, departmentName: "Human Resource" }
                        //1: { departmentID: 6, departmentName: "Machenical" }
                        //2: { departmentID: 7, departmentName: "Production" }

                        this.DepartmentName.setValue(this.preSelectDep);
                    }
                )
            }
        },
        err => { console.log(err) }
    )       
}
1

1 Answers

1
votes

I can't tell from the code, but have you declared a FormGroup above your use of formControlName? If not, then formControlName should be [formControl].

But assuming you are doing that part correctly, my next guess is that you are assigning a list of complex objects to the select list, but not defining a compareWith function, so the list doesn't know how to match up the values.

Take a look at that function (compareWith) in the Material docs for select-list: https://material.angular.io/components/select/api

I hope that helps.