【问题标题】:How to set selected on option in Angular 13?如何在 Angular 13 中设置选中的选项?
【发布时间】:2022-06-13 23:30:05
【问题描述】:

我目前正在努力以反应形式将所选值动态设置为我的选项之一。 我已经构建了一个编辑模式,如果我打开该编辑模式而不是空白选择,它应该将当前类别显示为选择选项。我的选项在选择时显示良好,但如果我想设置该值,它会以某种方式保持为空(未选中)。

目前我的选择是这样构建的

<select
      formControlName="categories"
      (change)="selectCategory($event)"
      class="form-select"
      id="categories">
      <option *ngFor="let category of categories"
              [value]="category.id">
        {{category.name}}
      </option>
</select>

我也尝试过像这样构建我的选项

<option *ngFor="let category of categories"
         [value]="category.id"
         [selected]="category === credential.category">

但这没有用。还尝试检查类别的 .name。

这是我的 .ts 文件的一部分。

public selectCategory(event: Event): void {
    const category: Category | undefined = this.categories.find((category: Category) => {
      return category.id === parseInt((event.target as HTMLInputElement).value);
    });

    this.credentialEditForm.get('category')?.setValue(category);
}

// called in the components ngOnInit() method
private initForm(): void {
    this.credentialEditForm = this.formBuilder.group({
      category: [this.credential.category, Validators.required],
      categories: this.categories,
    });
}

// called when I open the modal so the current values should be put in
// works on other fields the form has (I just didn't put them in here for the code to be shorter)
private fillFormWithInfo(): void {
    this.credentialEditForm.setValue({
      category: this.credential.category,
      categories: this.credential.category.name,
    });
}

我使用类别和类别作为表单字段,因为如果我只使用类别并选择一个选项,则选择字段也不会显示刚刚选择的值。

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    发现我的错误。我没有将我的类别字段设置为 id 而是名称。在我的 html 中,我还将选项的值设置为类别 ID,因此显然它也应该设置为代码中的 id。

    private fillFormWithInfo(): void {
        this.credentialEditForm.setValue({
          category: this.credential.category,
          categories: this.credential.category.id,
        });
    }
    

    【讨论】:

      【解决方案2】:

      我正在使用(参见“stuForm.patchValue”部分,stuCity 是 formControl 的下拉菜单):

            this.callApi.GetCities()
          .subscribe({
            next: (data) => {
              this.ethnRec = data;
              if (this.cityRecord)
              {
                this.stutForm.patchValue({
                  stuCity: this.cityRecord[0].id
                });
              }
            },
            error: (e) => {
      

      【讨论】:

        猜你喜欢
        • 2019-04-28
        • 1970-01-01
        • 2010-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-17
        • 2021-05-19
        • 1970-01-01
        相关资源
        最近更新 更多