在类selectpicker的下拉菜单中,课程没有动态加载。
我在angular中添加了带有selectpicker类的下拉列表。它被启动但仍然为空。从MongoDB获取课程后,将添加课程。我已经在ts文件的ngOnInit()函数中编写了获取课程的逻辑。但是,该数组当然不会显示在下拉选择器中。提取后,课程将在控制台中登录。 如果我直接在ngOnInit()中将数组分配给CourseAddChoices,它会在下拉菜单中加载值,但我是从MongoAtlas获取数据。
HTML文件代码
<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文件(它是大文件,但下面显示了ngOnInit函数)
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);
},
);
}
答案 0 :(得分:1)
该问题现已解决。主要原因是Bootstrap的selectpicker没有等待从数据库中获取数据。作为解决方案,我们可以在一段时间后刷新选择器。在获取数据1秒钟后,我刷新了selectpicker。为此,将数据从数据库中提取到ts文件后,请编写以下代码。
setTimeout(function () {
$('.selectpicker').selectpicker('refresh'); // refresh the selectpicker with fetched courses
}, 1000);
它将刷新选择器。需要使用npm install命令导入jQuery。
如果要在提交表单后使用默认值刷新选择器,只需添加val('default')如下。
setTimeout(function () {
$('.selectpicker').val('default').selectpicker('refresh'); // refresh the selectpicker with fetched courses
}, 1000);
特别感谢Wasim Akram。