Pari Baker
Pari Baker

Reputation: 716

angular 6 patchValue updates the value but not when I submit?

I am updating the value of a field on blur making it into a currency value on blur. When I type my value and leave the formcontrol the update on blur works and makes the value (20.00) to ($20.00) or (20.05060) to ($20.00) however when I click the generate form button it console.logs the value as it was before my patchValue. How can I fix that?

export class InvoicesComponent implements OnInit {
  invoiceGeneratorForm: FormGroup;
  subtotalSub: Observable<any>;
  subTotal = 0;
  itemPriceCurrent: Observable<any>;
  prices = [];
  constructor(public fb: FormBuilder, private currencyPipe: CurrencyPipe) {}

  ngOnInit() {
    this.invoiceGeneratorForm = this.fb.group({
      firstName: [""],
      lastName: [""],
      email: [""],
      itemsArray: this.fb.array([this.getItems()]),
      tax: [""],
      subTotal: [{ value: this.subTotal, disabled: true }],
      invoiceTotal: [""]
    });


  }
 private pushCurrentPrice(index: number){
  const control = <FormArray>this.invoiceGeneratorForm.controls["itemsArray"];
   const currentControl= control.at(index)['controls']['itemPrice'];
   const typeCheck = parseFloat(currentControl.value)||0;
   const subFormatted = this.currencyPipe.transform(
    typeCheck,
    "USD",
    "symbol-narrow",
    "1.2-2"
  );
   currentControl.patchValue(subFormatted,{onlySelf: true, emitEvent: false});
   console.log(currentControl);

 }
  private getItems() {
    return this.fb.group({
      itemName: ["", Validators.required],
      itemPrice: [
        "",
        Validators.compose([
          Validators.required
        ])
      ]
    });
  }
  private addItemRow() {
    const control = <FormArray>this.invoiceGeneratorForm.controls["itemsArray"];
    control.push(this.getItems());
  }
  private deleteItemRow(index: number) {
    const control = <FormArray>this.invoiceGeneratorForm.controls["itemsArray"];
    control.removeAt(index++);
  }

  onGenerateForm() {
    console.log(this.invoiceGeneratorForm.value);
  }
}

Upvotes: 2

Views: 824

Answers (1)

alokstar
alokstar

Reputation: 499

This is expected. You are using pipes which modifies your data on client side and do not change the actual value of the data. Pipes are used to process the data. Please read https://angular.io/guide/pipes which might give you more details.

Upvotes: 2

Related Questions