Angular 2删除或添加data.value对象的数据

时间:2017-11-30 10:15:35

标签: forms angular form-submit

我需要删除"玩具"在提交之前从 form.value 对象,并将新数据添加到' price'。但必须声明控件。

form.value object

{
  "red": 1,
  "green": 3,
  "black": "120",
  "blue": 3,
  "toys": [
    {
      "bear": 0,
      "soldier": 0,
      "car": 0
    }
  ],
  "price": [
    {
      "default": 123,
      "pre": 3,
      "after": 2
    },
    {
      "default": 3,
      "pre": 0,
      "after": 0
    }
  ]
}

ts

 initForm() {
        this.form = this._fb.group({
        red: 0,
        green: 0,
        black: '',
        blue: 0,
        toys: this._fb.array([this.inittoys()]),
        price: this._fb.array([this.initprice()]),

   });

HTML

 <div class="form-group">
   <label for="black">Max travel time</label>
    <select class="form-control" id="black" formControlName="black">
       <option *ngFor="let t of colors; let i=index" [ngValue]="i">{{t}}</option>
    </select>
</div> 

1 个答案:

答案 0 :(得分:1)

您可以在发送表单之前修改函数中的值,如下所示:

interface Expression : Equatable<Expression>
{   
    Expression subsitute(BoundVariable bound);
    Option<Value> evaluate(); // only expression with no free variables have a value
    // maybe a freeVariables, or a toString or whatever else is useful
}

class BoundVariable
{
    Expression body;
    Identifier name;
}

class FreeVariable : Expression
{
    Identifier name;
    Expression subsitute(BoundVariable bound)
    {
        return name == bound.name ? bound.body : this;
    }
    Option<Value> evaluate()
    {
        return new Option<Value>(); // None
    }
    bool Equals (Expression other)
    {
        if (other as FreeVariable) 
        {
            return name == other.name;
        }
        return false;
    }
}

class Add : Expression
{
    Expression left;
    Expression right;
    Expression subsitute(BoundVariable bound)
    {
        return new Add(left.substitute(bound), right.substitute(bound));
    }
    Option<Value> evaluate()
    {
        return from l in left.evaluate()
               from r in right.evaluate()
               select l + r;
    }
    bool Equals (Expression other)
    {
        if (other as Add) 
        {
            return left.Equals(other.left) && right.Equals(other.right);
        }
        return false;
    }
}

// Multiply, Subtract, Divide etc.
// It may be easier to have a bunch of wrappers for (binary) Function<Value, Value, Value> (unary) Function<Value, Value>, etc.

class Literal : Expression
{
    Value value;
    Expression subsitute(BoundVariable bound)
    {
        return this;
    }
    Option<Value> evaluate()
    {
        return value;
    }
    bool Equals (Expression other)
    {
        if (other as Literal) 
        {
            return value == other.value;
        }
        return false;
    }
}

...

在组件中:

<form [formGroup]="yourForm" (ngSubmit)="yourSendFunction(yourForm.value)">

}