如何从API检索选项时设置Mat-Select的默认值

时间:2018-05-23 11:22:52

标签: angular angular-material2 angular6

我有以下mat-select控件,其选项是从ngOnInit上的服务器动态加载的:

      <mat-form-field class="full-width">
        <mat-select placeholder="Category" formControlName="patientCategory">
          <mat-option>--</mat-option>
          <mat-option *ngFor="let category of patientCategories" [value]="category">
            {{category.name}} - {{category.description}}
          </mat-option>
        </mat-select>

        <mat-error *ngIf="form.controls['patientCategory'].hasError('required')">
          Please select a category
        </mat-error>
      </mat-form-field>

该控件是名为form的表单组的一部分,我使用this.formBuilder.group({})构建该表单。控件位于具有名为populateStep的函数的组件内。

populateStep(value: PatientStepModel) {
    // Set values of other controls..

    // Categories have been retrieved
    if (this.patientCategories.length > 0) {

      // Must set reference for MatSelect
      const toSelect = this.patientCategories.find(c => c.id == category.id);
      this.form.get('patientCategory').setValue(toSelect);

    } else {
      this.logger.trace('No categories exist, will set category at the end of HTTP call..');
      this.categoryToSelect = value.category;
    }
  }

如上面的代码所示,当外部组件调用populateStep函数时,该函数会检查是否已从服务器加载类别。如果有类别,我可以设置选择的值。

但是,如果类别为空,即HTTP调用仍在进行中,我必须设置categoryToSelect变量并在subscribe回调中进行相同的选择。

  private loadPatientCategories(): void {

    this.operationCategoryService.getAll()
      .subscribe(
        results => {
          this.patientCategories = results;

          if (this.categoryToSelect) {
            // Must set reference for MatSelect
            const toSelect = this.patientCategories.find(c => c.id == category.id);
            this.form.get('patientCategory').setValue(toSelect);
          }
        },
        error => {
          this.notificationService.openSnackBar('An error occurred');
        }
      );
  }

我对这个解决方案不满意,因为它要求我在多个地方做同样的事情,有更好的解决方案吗?也许在设置类别之前设置超时?虽然我不能确定HTTP调用需要多长时间..

0 个答案:

没有答案
相关问题