角反应形式模型 - 发送值,而不是描述

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

我对Angular 2+有很大的问题。我创建了组合框过滤器,它可以像这样使用来自数组的字典数据

[{
  value: 'fb',
  description: 'football'
}]

用户可以从过滤列表中选择一个字典项,或者将值写入输入元素,触发过滤器。

在此之后,app检查表单是否有效(表单中的字典存在于描述等)。我使用[value]标签将输入与表单绑定。

<input type="text" [value]="getSelectedSport.description"

问题 - 我的后端仅接受来自模型的“价值”,但此时,我发送说明。我可以解决这个问题,改变

getSelectedSport.description 

getSelectedSport.value, 

但这不正确,因为在形式上我只得到字段的“值”(短)值。

如何在不更改表示的情况下更改表单值?我不能使用提交事件来转换数据,因为我从父元素得到这个表单:(

<input class="form-control" type="text" (focus)="toggleVisible(true)" (blur)="handleBlur()" (keydown)="handleSelectActions($event)"
        [formControl]="selectedSport" [value]="getSelectedSport.value" [maxLength]="longestDescription">
      <ul class="select" [ngClass]="(isOptionVisible) ? 'isVisible' : 'isNotVisible'">
        <li *ngFor="let item of filterModel; index as i" class="option" (click)="selectItem(item.description)"
           [attr.data-order]="i" [ngClass]="this.focusedIndex === i ? 'selected' : ''">
          {{item.description}}
        </li>
      </ul>

ts文件(一些方法,下面链接到整个文件)

public get getSelectedSport(): AbstractControl {
    return this.selectedSport;
  }

public selectItem(item: any) {
    this.isOptionVisible = false;
    this.selectedSport.setValue(item)
  }

public handleBlur() {
    if (this.selectedSport.valid){
      this.isOptionVisible = false;
    }
  }

private selectViaEnter() {
    this.selectItem(this.filterModel[this.focusedIndex].description);
    this.focusedIndex = 0;
  }

https://github.com/Kamilnaja/filterComboBox/blob/master/src/app/combo/combo.component.ts https://github.com/Kamilnaja/filterComboBox/blob/master/src/app/combo/combo.component.html

angular typescript angular-forms
1个回答
0
投票

经过一段时间尝试通过试验结束错误解决此问题,我找到了答案。基本上,我们希望使用描述显示表单值,并在提交时发送模型值。为什么不使用两种形式。

在ts文件中,我添加了一个表单控件,它处理所有操作,但是具有其他formControlName而不是来自父表单的第一个表单组。

当表单值看起来正确时,我使用正确的对象值更新两个输入字段。下面是一些角度伪代码:

export class myComponent {
    myNewFormControl: FormGroup = new FormControl('');

    public selectItem(item: any) {
        this.isOptionVisible = false;
        this.selectedSport.setValue(item.value);
        this.myNewFormControl.setValue(item.description);
    }
}

所以现在,我可以从HTML中删除导致表单的第一个错误,并以我需要的形式显示模型描述。

<input formControlName="myNewFormControl" value=[item.description] /><!-- and other actions also here -->

在提交时,表单也提交了我需要的价值,所以我认为,这是正确答案。

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