如何在Angular中填充表单中的选择选项

问题描述 投票:0回答:1

我有一个包含许多选项的表单。我需要填充这些。最初通过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],
    });
  }
}
javascript angular select html-select
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.