只读/禁用输入未在 Angular 中提交 [英] Readonly/Disabled input not submitting in Angular

查看:28
本文介绍了只读/禁用输入未在 Angular 中提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular 2 中创建表单时遇到问题.我需要提交一些由服务动态生成的值.使用 Angular 的 http 模块,我得到一个价格,然后用户现在可以确切地知道多少比特币是 X 数量的智利比索.我要做的是提交所有这些数据.我不能这样做,因为角度表单没有提交禁用/只读输入.这些输入是汇率和目标金额(相当于 btc).

我尝试了模板驱动的方法和数据驱动的方法,但都没有成功.我什至无法在控制台中记录这些值.如果我从输入中删除 disabled 或 readonly 属性,这些值会记录在控制台中并提交到我的数据库.

感谢您花时间帮助我.这是我的代码:

component.ts

import { Component, OnInit } from '@angular/core';从'../services/exchange/surbtc.service'导入{ SurbtcService};从@angular/forms"导入 { FormBuilder, FormGroup, Validators, FormControl, NgForm };从 '../services/firedb.service' 导入 { FiredbService };从firebase/app"导入 * 作为 firebase;@成分({选择器:我的仪表板",templateUrl: './dashboard.component.html'})导出类 DashboardComponent {//myForm2: FormGroup;//错误=假;//错误信息 = '';构造函数(私有 surbtcService:SurbtcService,私有 fb:FormBuilder,私有 dbfr:FiredbService){/*this.myForm2 = this.fb.group({电子邮件:['',Validators.email],clpmount: ['', Validators.required],btcmount: [''],速度: [''],描述:['']});*/}//形式信息 = {速度: '',比特币:''};onSub() {控制台日志(this.info);}//周边服务价格:任意;基数:1;获取汇率(){返回 this.prices * 0.989}获取目标金额(){返回 this.baseAmount/this.exchangeRate;}ngOnInit() {this.surbtcService.getPrices().订阅(价格=> {this.prices = 价格.ticker.min_ask[0];console.log(prices.ticker.min_ask[0]);});} }

正如你在我的代码中看到的,数据驱动的方法除了用于提交表单的函数外都被注释了.

html:

<div class="form-group"><md-input-container class="full-width"><input mdInput type="number" id="montoclp" name="clpmount" placeholder="Ingrese el monto en CLP" [(ngModel)]="baseAmount" name="clp"></md-input-container><md-input-container class="full-width"><input mdInput class="form-control" name="btcmount" [ngModel]="info.btcmount" placeholder="Monto en BTC" id="vat" [value]="targetAmount | number:'1.8-8'"只读></md-input-container><md-input-container class="full-width"><input mdInput class="form-control" name="rate" [ngModel]="info.rate" placeholder="Tasa de cambio" id="street" [value]="exchangeRate | number:'1.0-0'"只读></md-input-container><md-input-container class="full-width"><input mdInput type="mail" class="form-control" ngModel name="email" placeholder="E-mail cliente (Opcional)"></md-input-container><md-input-container class="full-width"><input mdInput type="text" class="form-control" ngModel name="descripcion" placeholder="Descripción pago (Opciona)"></md-input-container>

<button md-raised-button type="submit" color="primary" class="btn-w-md">确认</button><div class="dividerdivider-sm"></div></表单>

再次感谢!

编辑!!!:

数据驱动的 html:

 <div class="form-group"><md-input-container class="full-width"><input mdInput type="number" id="montoclp" name="clpmount" placeholder="Ingrese el monto en CLP" formControlName="clpmount" [(ngModel)]="baseAmount"></md-input-container><md-input-container class="full-width"><input mdInput class="form-control" name="btcmount" placeholder="Monto en BTC" formControlName="btcmount" [value]="targetAmount | number:'1.8-8'"></md-input-container><md-input-container class="full-width"><input mdInput class="form-control" name="rate" formControlName="rate" placeholder="Tasa de cambio" [value]="exchangeRate | number:'1.0-0'"></md-input-container><md-input-container class="full-width"><input mdInput type="mail" class="form-control" formControlName="email" name="email" placeholder="E-mail cliente (Opcional)"></md-input-container><md-input-container class="full-width"><input mdInput type="text" class="form-control" formControlName="descripcion" name="descripcion" placeholder="Descripción pago (Opciona)"></md-input-container>

<button md-raised-button type="submit" color="primary" class="btn-w-md">确认</button><div class="dividerdivider-sm"></div></表单>

解决方案

您可以使用 getRawValue(),它为您提供所有表单值,甚至是禁用的值.

所以当你的表单看起来像这样时:

this.myForm2 = this.fb.group({电子邮件:['',Validators.email],clpmount: ['', Validators.required],btcmount: [{value: '', disabled: true}],....});

使用

this.myForm2.getRawValue()

将包含在上面的示例中 btcmount 值.

看到模板...在反应形式中,Angular 无视 value[value].我们可以克服这个问题并使用单向绑定,我也建议您使用您的字段 clpAmount 并设置 [ngModel]="baseAmount".为什么?好吧,首先 ngModel 指令甚至不包含在 ReactiveFormsModule 中,因此,即使在文档中没有明确提及,我们也可以假设它们不应该包含在一起使用.我们也可以理解,如果将[(ngModel)]一起使用,我们会有两个双向绑定,这有时会导致问题.

[ngModel] 更好,因为 Angular 只是将值从 TS 绑定到模板,并不真正关心接下来会发生什么.在某些情况下,[ngModel] 在响应式形式中很有用,这是其中一种情况.即使响应式表单忽略 value,它也不会忽略 ngModel,所以我们可以在这里使用它!所以将 [value][ngModel] 交换:

<input mdInput formControlName="rate" placeholder="Tasa de cambio" [ngModel]="exchangeRate | number:'1.0-0'">

现在您拥有使用 getRawValue() 时的所有值 :)

I've been having problems creating a form in Angular 2. I need to submit some values that are dinamically generated by a service. Using the http module of Angular I get a price and then the user can now exactly how much bitcoin is an X amount of chilean pesos. What I'm trying to do is submit all that data. I can't do it because angular forms are not submitting the disabled/readonly inputs. These inputs are the exchange rate and the target amount (equivalent in btc).

I tried the template driven approach and the data driven approach with no success. I can't even log the values in the console. If I remove disabled or readonly property from the inputs the values are logged in the console and submitted to my database.

Thanks for taking the time to help me. This is my code:

component.ts

import { Component, OnInit } from '@angular/core';
import { SurbtcService } from '../services/exchange/surbtc.service';
import { FormBuilder, FormGroup, Validators, FormControl, NgForm } from "@angular/forms";
import { FiredbService } from '../services/firedb.service';
import * as firebase from 'firebase/app';

@Component({
  selector: 'my-dashboard',
  templateUrl: './dashboard.component.html'
})
export class DashboardComponent {

  //myForm2: FormGroup;
  //error = false;
  //errorMessage = '';

  constructor(private surbtcService: SurbtcService, private fb: FormBuilder, private dbfr: FiredbService) {
/*
          this.myForm2 = this.fb.group({
            email: ['', Validators.email],
      clpmount: ['', Validators.required],
      btcmount: [''],
      rate: [''],
      descripcion: ['']

        });
 */  }
//Form

info = {
  rate: '',
  btcmount: ''
};


onSub() {
 console.log(this.info);
  }



  //surbtcservice

  prices: any;
  baseAmount: 1;

  get exchangeRate() {
   return this.prices * 0.989
    }

  get targetAmount() {
   return this.baseAmount / this.exchangeRate;
    }

  ngOnInit() {
     this.surbtcService.getPrices()
      .subscribe(prices => {
       this.prices = prices.ticker.min_ask[0];
       console.log(prices.ticker.min_ask[0]);
        });
    } }

As you can see in my code, the data driven approach is commented except for the function used to submit the form.

html:

<form (ngSubmit)="onSub(f)" #f="ngForm">
          <div class="form-group">
            <md-input-container class="full-width">
              <input mdInput type="number" id="montoclp" name="clpmount" placeholder="Ingrese el monto en CLP" [(ngModel)]="baseAmount" name="clp">
            </md-input-container>
            <md-input-container class="full-width">
              <input mdInput class="form-control" name="btcmount" [ngModel]="info.btcmount" placeholder="Monto en BTC" id="vat" [value]="targetAmount | number:'1.8-8'" readonly>
            </md-input-container>
            <md-input-container class="full-width">
              <input mdInput class="form-control" name="rate" [ngModel]="info.rate" placeholder="Tasa de cambio" id="street" [value]="exchangeRate | number:'1.0-0'" readonly>
            </md-input-container>
            <md-input-container class="full-width">
              <input mdInput type="mail" class="form-control" ngModel name="email" placeholder="E-mail cliente (Opcional)">
            </md-input-container>
            <md-input-container class="full-width">
              <input mdInput type="text" class="form-control" ngModel name="descripcion" placeholder="Descripción pago (Opciona)">
            </md-input-container>
          </div>
          <button md-raised-button type="submit" color="primary" class="btn-w-md">Confirmar</button><div class="divider divider-sm"></div>
        </form>

Thanks again!

EDIT!!!:

data driven html:

            <form [formGroup]="myForm2" (ngSubmit)="onSub()">
              <div class="form-group">
                <md-input-container class="full-width">
                  <input mdInput type="number" id="montoclp" name="clpmount" placeholder="Ingrese el monto en CLP" formControlName="clpmount" [(ngModel)]="baseAmount">
                </md-input-container>
                <md-input-container class="full-width">
                  <input mdInput class="form-control" name="btcmount" placeholder="Monto en BTC" formControlName="btcmount" [value]="targetAmount | number:'1.8-8'">
                </md-input-container>
                <md-input-container class="full-width">
                  <input mdInput class="form-control" name="rate" formControlName="rate" placeholder="Tasa de cambio" [value]="exchangeRate | number:'1.0-0'">
                </md-input-container>
                <md-input-container class="full-width">
                  <input mdInput type="mail" class="form-control" formControlName="email" name="email" placeholder="E-mail cliente (Opcional)">
                </md-input-container>
                <md-input-container class="full-width">
                  <input mdInput type="text" class="form-control" formControlName="descripcion" name="descripcion" placeholder="Descripción pago (Opciona)">
                </md-input-container>
              </div>
              <button md-raised-button type="submit" color="primary" class="btn-w-md">Confirmar</button><div class="divider divider-sm"></div>
            </form>

解决方案

You can use getRawValue(), which gives you all form values, even the disabled ones.

So when your form looks something like this:

this.myForm2 = this.fb.group({
  email: ['', Validators.email],
  clpmount: ['', Validators.required],
  btcmount: [{value: '', disabled: true}],
  ....
});

using

this.myForm2.getRawValue()

will include in above example btcmount value.

EDIT:

Seeing the template... In reactive forms, Angular disregards value and [value]. We can overcome this and use one-way binding, which I also suggest you do with your field clpAmount and set [ngModel]="baseAmount". Why? Well, first of all the ngModel directive isn't even included in ReactiveFormsModule, so from that, even not clearly mentioned in docs, we can all but assume they should not be used together. We can also understand it, if using [(ngModel)] together, we would have two bidirectional bindings, which can sometimes cause issues.

[ngModel] is better, since Angular just binds the value from TS to template, and doesn't really care what happens next. In some cases, [ngModel] can be useful in reactive forms, this is one of those cases. Even though reactive forms ignore value, it does not ignore ngModel, so we can use that just fine here! So exchange [value] with [ngModel]:

<input mdInput  formControlName="btcmount" [ngModel]="targetAmount | number:'1.8-8'">

<input mdInput formControlName="rate" placeholder="Tasa de cambio" [ngModel]="exchangeRate | number:'1.0-0'">

Now you have all values when you use getRawValue() :)

这篇关于只读/禁用输入未在 Angular 中提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆