I am creating a dynamic form field using angular. I want to set a value to an input whenever there is changes

Viewed 33
  constructor(private orderService: OrderService, private fb: FormBuilder, public dialog: MatDialog, public snackBar: MatSnackBar, private productService: ProductService) { 
    this.orderForm = this.fb.group ({ //form validator for create and update
      '_id': [ "" ],
      'orderClientName': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-zA-Z\s]*$/), Validators.minLength(1), Validators.maxLength(50)]) ],
      'orderContact': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]*$/), Validators.minLength(11), Validators.maxLength(11)]) ],
      'orderItem': this.fb.array([ this.createItem() ]),
      'orderDiscount': [ "", Validators.compose([Validators.pattern(/^[0-9]*$/), Validators.minLength(1), Validators.maxLength(20)]) ],
      'orderTotal': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]*$/), Validators.minLength(1), Validators.maxLength(5)]) ]
    });
  }


  createItem(): FormGroup {
    return this.fb.group({
      'productId': [ "", Validators.compose([Validators.required, Validators.pattern(/^[a-f\d]{24}$/i), Validators.minLength(24), Validators.maxLength(24)]) ],
      'productPrice': [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
      'productQuantity' : [ "", Validators.compose([Validators.required, Validators.pattern(/^[0-9]\d*$/), Validators.min(1), Validators.max(99999)]) ],
    });
  }

this is my form group and i want to set value to productPrice whenever there are changes in productId. but I do not know how to set value.

  getPrice(index){
    let a = this.orderForm.value.orderItem[index]['productPrice'].patchValue({productPrice: "12"});
    console.log(a);
  }

and the code above is not working. How to fix it?

1 Answers

You need to extract the orderItem first and then assign the value to productPrice

let arr = this.orderForm.controls['orderItem'].value 
arr[0].patchValue({
  {productPrice: "12"}
});
Related