1

I have a problem since i need to select a warehouse first before i can see the ingredients. My problem is when i try to change another warehouse, how can i clear the form array or the WHOLE FORM because each warehouse has different set of ingredients? I tried to do this this.form = new FormGroup({}) but it destroys the subscription. How can i do this? Here's my code below.

constructor(private fb: FormBuilder,
            private stocksRequestService: StocksRequestService,
            private warehouseService: WarehouseService) { 

    this.form = new FormGroup({});

            this.form.setControl('ingredients', new FormArray([]));
            this.ingredientsFormArray = <FormArray>this.form.controls['ingredients'];
        }

    ngOnInit() {
            this.getAllWarehouse();

            this.subscription = this.route.params
            .subscribe((params: Params) => {
                this.id = +params['id'];
                this.stocksRequestService.getStockRequest(this.id)
                .subscribe(
                    (data:any) => {
                        this.request = data[0];
                        console.log(data);

                    },
                    error => {
                        console.log(error);
                        alert("ERROR");
                    })
            });



        }

        initializeForm() {
            this.initializeIngredientsFormArray();
        }

        initializeIngredientsFormArray() {
            this.request2.delivery_items.forEach(ingredient => {
                this.ingredientsFormArray.push(new FormGroup({
                    id: new FormControl(ingredient.id),
                    sku: new FormControl(ingredient.ingredient.SKU),
                    name: new FormControl(ingredient.ingredient.name),
                    requested_qty: new FormControl(ingredient.request_quantity),
                    approved_qty: new FormControl(ingredient.approved_quantity),
                    available_approved_qty: new FormControl(ingredient.approved_quantity - ingredient.delivered_quantity),
                    unit: new FormControl(ingredient.unit.name),
                    quantities: new FormArray([]),
                }));
                console.log(this.ingredientsFormArray);

                const ingredientForm = <FormGroup>this.ingredientsFormArray.controls[this.ingredientsFormArray.length-1];
                const singleIngredientFormArray = <FormArray>ingredientForm.controls['quantities'];
                ingredient.ingredient.warehouse_items.forEach(element => {
                    singleIngredientFormArray.push(this.initializeSingleQuantityForm(element));

                });
            });
        }

        initializeSingleQuantityForm(quantity: any): FormGroup {
            return new FormGroup({
                warehouse_item_id: new FormControl(quantity.id),
                unit_id: new FormControl(quantity.unit),
                ingredient_id: new FormControl(quantity.ingredient_id),
                expiration_date: new FormControl(quantity.expiration_date),
                available_warehouse_qty: new FormControl(quantity.available_stocks),
                transfer_qty: new FormControl('', [Validators.required]),
            });
        }

        onSelectWarehouse(event): void {
            const formData = {
                warehouse_id: event.target.value,
                request_stock_id: this.id
            }
            console.log(formData);
            this.warehouse_id =  event.target.value
            this.subscription = this.stocksRequestService.selectIngredient(formData)
            .subscribe(
                (data:any) => {
                    this.request2 = data.requestStock[0];
                    console.log(data); 

                    // HOW TO CLEAR FORM ARRAY HERE

                    this.initializeForm(); 


                },
                error => {
                    alert("Error! Can't Select Warehouse");
                    console.log(error); 
                })
        }

        getAllWarehouse() {
            this.subscription = this.warehouseService.getAll()
            .subscribe(
                (data:any) => {
                    this.warehouses = data.warehouses;
                    console.log(data);
                },
                error => {
                    console.log(error);
                });
        }

2 Answers 2

2

you can make your formarray empty by doing the following

const arr = <FormArray>this.form.controls.ingredients;
      arr.controls = [];
Sign up to request clarification or add additional context in comments.

Comments

-1

You can call this.form.reset() to clear the form. In order to delete everything from the FormArray while maintaining the subscription you could remove elements one-by-one:

resetFormArray = (formArray: FormArray) => {
    while (formArray.length !== 0) {
        formArray.removeAt(0)
    }
}

3 Comments

I mean when i select another value from the dropdown. It should clear everything not one by one. Also i didnt use form.reset() because i want the whole formarray to be cleared up
Well, if you call this function and pass your array into it it will clear the array without breaking the subscription. Have you tried this out? Is it not working the way you want it to?
Add the code form the answer above as a method to the component. Right where you have the comment "// HOW TO CLEAR FORM ARRAY HERE" write this.resetFormArray (this.ingredientsFormArray); It should clear the array after the warehouse has been changed and before calling the init method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.