在Angular 8中动态加载“select”选项的解决方法如下:
在Angular项目中创建一个名为dynamic-select
的组件。
在dynamic-select.component.ts
文件中,导入必要的模块和服务:
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { ApiService } from 'path/to/api.service';
export class DynamicSelectComponent implements OnInit {
dynamicForm: FormGroup;
selectOptions: any[];
constructor(private apiService: ApiService) {}
ngOnInit() {
this.dynamicForm = new FormGroup({
selectControl: new FormControl('')
});
this.loadSelectOptions();
}
loadSelectOptions() {
this.apiService.getSelectOptions().subscribe((response: any[]) => {
this.selectOptions = response;
});
}
}
dynamic-select.component.html
文件中,使用Angular的模板语法创建一个select
元素,并使用ngFor
指令循环迭代selectOptions
数组,生成option
元素:
ApiService
来从回调中加载“select”选项。在api.service.ts
文件中,创建一个方法getSelectOptions()
,并使用HttpClient
模块发送HTTP请求:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) {}
getSelectOptions() {
return this.http.get('path/to/select/options');
}
}
dynamic-select
组件:
这样,当父组件被渲染时,dynamic-select
组件将自动加载“select”选项并显示在页面上。