首页 > 解决方案 > 如何在 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],
    });
  }
}

标签: javascriptangularselecthtml-select

解决方案


您需要在.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/


推荐阅读