Home > Software design >  Dropdown (select option) not getting data - Angular 11
Dropdown (select option) not getting data - Angular 11

Time:07-25

Here is my model.ts

export interface IUserEducationalBackground {
    id: number;
    user_id: number;
    studies_type: string;
    year: number;
    course: string;
}

I have a dropdown like this.

<div >
  <ng-select bindLabel="name" bindValue="name" [items]="studiesType" [(ngModel)]="studiesType.name"
  (Change)="searchStudies(studiesType.name)">
  </ng-select>
</div>

whenever this value is change i want to change html table data

<tr *ngFor="let item of educationalDetails; let i = index">
  <td>
    {{ item.year }}
  </td>
  <td>
    {{ item.course }}
  </td>
  <td>
    {{ item.awards }}
  </td>
</tr>

Here's is my array i want to compare to api data

studiesType: any = [
    { name: 'Basic' },
    { name: 'Secondary' },
    { name: 'Undergraduate' },
    { name: 'Graduate' },
  ];

UPDATE
This is my method to find user studies

public searchStudies(name: any) {
    let obj = this.educationalData.filter(m => m.Name == name);
    console.log(this.educationalData)
    this.educationalDetails = obj;
    console.log(this.educationalDetails)
  }

This is my api call.

private getUserEducationalBackground(user): void {
    this.apiService.getUserProfile('users/educational-background', user.id)
      .subscribe(
        data => {
          this.educationalData = data;
        });
  }

When i console.log it gives the value of console.log(this.educationalData) but after that console.log(this.educationalDetails) gives blank array. enter image description here

CodePudding user response:

Issue 1: Consider using another variable for storing selected studiesType.

HTML

<ng-select bindLabel="name" bindValue="name" [items]="studiesType" 
    [(ngModel)]="selectedStudiesType"
    (change)="searchStudies(selectedStudiesType)">
</ng-select>

TS

selectedStudiesType: string;

Issue 2: There are few errors in the filtering logic.

  1. Missing Name property. Instead, use studies_type.

  2. Compare both strings with ignoring case sensitive.

public searchStudies(name: any) {
  let obj = this.educationalData.filter(
    (m) => m.studies_type == name.toLowercase()
  );

  this.educationalDetails = obj;
}

Sample StackBlitz Demo

  • Related