Chintan Patel
Chintan Patel

Reputation: 133

data not getting loaded dynamically in selectpicker in angular

Courses are not getting loaded dynamically in dropdown with class selectpicker.

I have added dropdown with selectpicker class in angular. It gets initiated but remains empty. The courses are to be added after being fetched from MongoDB. I have written course fetching logic in ngOnInit() function of ts file. But the array of course is not getting displayed in dropdown selectpicker. The courses are getting logged in console after fetching. If I directly assign array to CourseAddChoices in ngOnInit(), it loads value in dropdown, but I am fetching data from MongoAtlas.

HTML file code

<label class="col-sm-3 col-form-label">Courses</label>
    <div class="col-sm-4">
        <div class="input-group-prepend ">
        <div class="addPrepend input-group-text bg-success">
            Add
        </div>
        <select class="selectpicker" multiple data-live-search="true" id="add_courses" name="add_courses" (ngModel)="add_courses" #add_course="ngModel">
            <option *ngFor="let course of CourseAddChoices" [value]="course">{{course}}
            </option>
        </select>
    </div>
</div>

ts file (It is large file, but the ngOnInit function is shown below)

CoursesList: any[] = [];   // all courses which are offered
UserData: any[] = [];   // user data
UserRegisteredCourses: any[] = [];   // Courses which the user have completed
CourseAddChoices: any[] = [];   // Courses which user can add as registered
TempArray: any[] = [];   // This array will be used in checking difference in CoursesList and UserRegisteredCourses

ngOnInit() {
    this.authenticationService.authenticate();

    // fetch courses using getcourse service
    this._courseService.fetchCourses().subscribe(
      data => {
        this.CoursesList = data['Courses'];

        this._userdata.fetchUserData().subscribe(
          data => {
            this.UserData = data['User'];
            this.UserRegisteredCourses = data['User']['courses'];

            for (var i = 0; i < this.CoursesList.length; i++) {
              this.TempArray[this.CoursesList[i]['Name']] = true;
            }

            for (var i = 0; i < this.UserRegisteredCourses.length; i++) {
              if (this.TempArray[this.UserRegisteredCourses[i]]) {
                delete this.TempArray[this.UserRegisteredCourses[i]];
              }
            }

            for (var course in this.TempArray) {
              this.CourseAddChoices.push(course);
            }
          },
          error => {
            console.log("UserProfileFetchError: ", error);    
          }
        );
      },
      error => {
        console.log("CourseFetchError: ", error);
      },
    );

  }

Upvotes: 1

Views: 775

Answers (1)

Chintan Patel
Chintan Patel

Reputation: 133

The problem has been solved now. The main reason was selectpicker of Bootstrap which was not waiting to fetch data from database. As a solution, we can refresh the selectpicker after some time. I refreshed the selectpicker after 1 second of fetching the data. To do so, write the below code once you complete fetching the data from database into ts file.

setTimeout(function () {
   $('.selectpicker').selectpicker('refresh');   // refresh the selectpicker with fetched courses
}, 1000);

It will refresh the selectpicker. It is needed to import jQuery using npm install command.

If you want to refresh selectpicker with default value once form has been submitted, just add val('default') as below.

setTimeout(function () {
   $('.selectpicker').val('default').selectpicker('refresh');   // refresh the selectpicker with fetched courses
}, 1000);

Special thanks to Wasim Akram.

Answer link: https://stackoverflow.com/a/55257919/8243992

Upvotes: 1

Related Questions