javascript - 如何在 Angular 的表单中填充选择选项
问题描述
我有一个包含许多选择选项的表格。我需要填充这些。最初通过 JSON,但后来我将从我的数据库中填充。
我该怎么做。
这将是我的 html。
<div class="container mt-4">
<div class="card">
<form>
<div class="card-header">Search for a Property</div>
<div class="card-body">
<!-- County and Town Label-->
<div class="row">
<div class="col-md-6">
<label class="ml-1" for="county">County</label>
</div>
<div class="col-md-6">
<label for="town">Town</label>
</div>
</div>
<div class="row">
<!-- County Column -->
<div class="col-md-6">
<select class ="form-control" id="county" name="county">
</select>
</div>
<div class="col-md-6">
<select class="form-control" name="town">
</select>
</div>
</div>
</div>
</form>
</div>
</div>
这将是我的 js。
有没有办法为我需要的每个选择填充数组并循环遍历每个项目。
export class PropertySearchComponent implements OnInit {
searchForm: FormGroup;
constructor(private advertService: AdvertService, private alertify: AlertifyService, private formBuilder: FormBuilder) { }
ngOnInit() {
this.createSearchForm();
}
createSearchForm() {
this.searchForm = this.formBuilder.group({
town: [, Validators.required],
county: [, Validators.required],
});
}
}
解决方案
您需要在.ts
文件中填充一些数组(我假设您使用的是 TypeScript),例如:
counties: string[] = ['County1', 'County2', 'County3'];
然后在模板文件中:
<select class ="form-control" id="county" name="county">
<option value="">Please select a county</option>
<option *ngFor="let county of counties"
[value]="county">{{county}}
</option>
</select>
Angular 只需要知道要循环的内容并在模板中引用它。这是一个很好的参考:https ://codecraft.tv/courses/angular/forms/model-driven/
推荐阅读
- java - 如何使用 JSOUP 提取 css 样式
- reactjs - 类型“EventTarget & HTMLSelectElement”上不存在属性“值”
- java - 当从数据库中获取数据时,只获取一行的第一个索引,我想要每一行的所有数据
- c - 是否可以在函数中获取由返回值初始化的变量的内存地址?
- python - 无法完成操作:Elasticsearch AWS 中的 create_index
- c# - 通过正则表达式将括号中的字典键替换为值
- c# - 是否有通用解决方案来防止/避免在 web api C# 中过度发布?
- sharepoint - Sharepoint GetFileByServerRelativeUrl 返回文件不存在
- openid - 未找到 node-oidc-provider 授权码
- powerbi - 在这种情况下使用“计算”与不使用有区别吗?