0

I have got shop values(array of string) from another component and saved it to localstorage. Now I want to add this values into formarray named shopIds.There will not be any input form field in HTML file. But after form sumbit shopIds are getting null. How can I do this. I am adding codes here:

ngOnInit(): void {
    this.formInit();
    const shopIdsStr = localStorage.getItem('cdk-shop-list');
    if (shopIdsStr) {
      this.shop = JSON.parse(shopIdsStr);
      console.log(this.shop);
    }
  }

formInit = () => {
    this.couponForm = new FormGroup({
      shopIDs: this.formBuilder.array([this.shop]),
    });
  };

this is the log of this.shop

1 Answer 1

1

You are creating the form before getting values from the local storage. That's why the value is null.

Update: Since you are only storing static data which will not have any input control, you should not use FromArray. Instead, use a FromControl and set its value to the array of strings. It will be passed to the backend in the form of an array (just like your scenario).

formInit = () => {
    this.couponForm = new FormGroup({
      shopIDs: new FormControl(this.shop), //Set default value to shop array
    });
  };

Form Array aggregates the values and validity state of its child controls. It holds an array of Abstract controls.

That's why you were getting errors like Cannot read property '_rawValidators' of undefined


Call the this.forminit() method after reading values from local storage.

this.shop=[]; // Or initialize it with null according to your Backend contract.
ngOnInit(): void {
   
    const shopIdsStr = localStorage.getItem('cdk-shop-list');
    if (shopIdsStr) {
      this.shop = JSON.parse(shopIdsStr);
      console.log(this.shop);
    }
     this.formInit(); //Call Here
  }
Sign up to request clarification or add additional context in comments.

2 Comments

I have initialized like this : shop: string[] = []; Now after calling formInit down there there's some error in console like this: 1. this.validator is not a function 2. Cannot read property '_rawValidators' of undefined 3. Cannot read property 'get' of undefined
Updated my answer with the correct approach for your scenario

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.