我有这个非常简单的选择。我想在打开页面时只有一个选项。
<select class="custom-select form-control" id="coreBankingProject" name="coreBankingProject" readonly="true">
<option>{{settings.coreBankingProject}}</option>
</select>
然后我点击一个按钮
<button type="button" class="btn btn-primary-outline" (click)="getGitlabProjects()"><span class="fa fa-download"></span> Get projects</button>
我运行一个获取项目列表的函数。
getGitlabProjects() {
this.gitlabService.getProjects(this.gitlabUrl, this.gitlabToken).subscribe(projects => {
this.projects = projects;
})
}
我现在如何清理该选项并在那里插入项目?我想显示项目名称project.name
,我还需要删除readonly属性。
编辑:我当前的代码仅显示上次选择中的选项。我有4个选择。
getGitlabProjects() {
this.gitlabService.getProjects(this.gitlabUrl,this.gitlabToken).subscribe(projects => {
this.projects = projects;
this.btnGetProjectsClicked = true;
console.log(projects);
let coreBankingProjectSelect = document.getElementById("coreBankingProject");
let customerUIProjectSelect = document.getElementById("customerUIProject");
let adminUIProjectSelect = document.getElementById("adminUIProject");
let clientUIProjectSelect = document.getElementById("clientUIProject");
//remove previous options
coreBankingProjectSelect.innerHTML = '';
customerUIProjectSelect.innerHTML = '';
adminUIProjectSelect.innerHTML = '';
clientUIProjectSelect.innerHTML = '';
for(let i=0;i<projects.length;i++) {
let option = document.createElement("option");
option.text = projects[i].name;
option.value = projects[i].name;
//append projects
coreBankingProjectSelect.appendChild(option);
customerUIProjectSelect.appendChild(option);
adminUIProjectSelect.appendChild(option);
clientUIProjectSelect.appendChild(option);
}
// remove readonly
coreBankingProjectSelect.removeAttribute("readonly");
customerUIProjectSelect.removeAttribute("readonly");
adminUIProjectSelect.removeAttribute("readonly");
clientUIProjectSelect.removeAttribute("readonly");
})
}
答案 0 :(得分:0)
插入选项:
select = document.getElementById('coreBankingProject');
select.innerHTML = '';
for (index = 0; index < this.projects.length; ++index) {
const p = this.projects[index];
if (index === 0){
opt.setAttribute("selected", "selected");
}
var opt = document.createElement('option');
opt.value = p.name;
opt.innerHTML = p.name;
select.appendChild(opt);
}
删除只读:
select.removeAttribute('readonly');
答案 1 :(得分:0)
我看到有人已经得到了答案的removeAttribute部分,如果你还想从select中删除以前的选项,你可以在vbuzze建议的for循环之前添加以下内容。
select.innerHTML = '';