【问题标题】:How to get the input value written by interpolation code using Reactive Forms?如何使用 Reactive Forms 获取插值代码写入的输入值?
【发布时间】:2019-08-06 23:06:06
【问题描述】:

在这种情况下,我使用的是响应式表单而不是 ngModel

我正在将插值写入输入文本字段

当我提交我的表单时,我会得到所有字段值,除了插值的值。 插值是空的

如何解决??

<label class="form-control-sm"
         id="identificationCode"
         name="identificationCode">{{reference.value + "-" + publishDate.value}}
</label>
<input  #txtIdCode
         type="text" 
         id="idCode" 
         name="idCode"
         formControlName="txtIdCode"
         maxlength="15"                     
         value="{{reference.value + '-' + publishDate.value}}">

当我以这种方式获取 txtIdCode 时,我得到一个空值但输入文本被填充:

item.identificationCode = this.myForm.controls["txtIdCode"].value;

【问题讨论】:

    标签: javascript html angular visual-studio-code


    【解决方案1】:

    更改value 属性不会影响FormControl。在更改输入字段之前,它将保持为空。

    在您的情况下,将模板引用变量与ViewChild 绑定将起作用。

    组件.ts

      @ViewChild('txtIdCode')
      txtIdCode: ElementRef
      ...
    
      submit() {
        item.identificationCode = txtIdCode.nativeElement.value
      }
    

    【讨论】:

      【解决方案2】:

      使用属性绑定

      [value]="reference.value + '-' + publishDate.value"
      

      【讨论】:

        【解决方案3】:

        您不应该将value 与表单控件一起使用,您需要将实际值设置为表单控件本身:

        示例:

        this.myForm = this.fb.group({
          txtIdCode: [this.reference.value + "-" + this.publishDate.value]
        });
        

        如果您在创建表单时不知道值,请使用patchValue()

        this.myForm.get('txtIdCode')
          .patchValue(this.reference.value + "-" + this.publishDate.value)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-23
          • 2021-04-10
          • 2022-12-09
          • 1970-01-01
          相关资源
          最近更新 更多