Home > front end >  i have problem with angular formarray TypeError: Cannot read properties of undefined (reading '
i have problem with angular formarray TypeError: Cannot read properties of undefined (reading '

Time:11-12

hi guys i have two models category and product i wanna add category and multiple products in the same form using FormArray,the problem is when i try it in local array it works perfectly but when i try it with my models it not working at all

EXp

this this case it works in local array

 formData = {
    nom:'',
    products:[
      {
        nom:'',
        prix:0,
      }
    ]
  }

but when i call my Category model it not working (change it to category)

formData = new Category();

this is my category model

import { Product } from "./product"

export class Category {
    idcategory!: number
    nom!: string
    products!:Product[]

}

this is my component form

export class AddcatprodapiComponent implements OnInit {
  isSubmitted:boolean =false;
  count=0;
  formData = new Category();
  constructor( private fb:FormBuilder,private categoryService : CategoryService) { }

  ngOnInit(): void {

  }

  myReactiveForm = new FormGroup({
    
    nom:new FormControl(null),
    products:new FormArray([]),
  });

  addMember(){
    this.count  ;
   
    
    if(this.count >=2){
      this.formData.products.push({
        nom:'',
        prix:0
      })
    }

    this.members.push(this.memberAdded())
  }

  get members() :FormArray {
    return this.myReactiveForm.get('products') as FormArray;
    
  }

  memberAdded(){
    return this.fb.group({
      nom: [''],
      prix:['']
    })
  }

  removeMember(){
    this.isSubmitted= false;
    
    this.members.removeAt(this.members.length-1);
    this.count--;
    this.formData.products.splice(this.count)
  }

  onSubmit(form:FormGroup){
    
    this.isSubmitted = true;
    this.formData.nom= form.value.nom;
    for(let i=0;i< this.count;i  ){
      this.formData.products[i].nom=form.value.products[i].nom;
      this.formData.products[i].prix=form.value.products[i].prix;
    }

     this.categoryService.addcategory(this.formData).subscribe(
      prod => {console.log(prod); 
   
    }); 
  }

}

and this is my view in html

<form  [formGroup]="myReactiveForm" (ngSubmit)="onSubmit(myReactiveForm)">
    <label for="">nom</label>
    <input type="text"  formControlName="nom">
    
    <h5>product</h5>

    <button (click)="addMember()"  type="button">add</button>
    <br>
    <button (click)="removeMember()"  type="button">remove</button>
    <br>

    <div formArrayName="products">

            <div *ngFor="let member of members?.controls; let i=index">
                <div [formGroupName]="i">
                <label for="">nom prod</label>
                <input type="text"  formControlName="nom">
                <label for="">prix</label>
                <input type="text"  formControlName="prix">
            </div></div>

    </div>
<button >submit</button>
</form>

in local array everything works perfectly but when i change it to new Category i faced this problem

enter image description here

CodePudding user response:

There are two problems

  • Product property needs to be initialised.
  • Due to this condition this.count >=2, this.formData.products remains empty which will throw an error.

So either add a default value for products while initialising Category or do not allow the form to be submitted if the there is only one product

export class Category {
  idcategory!: number
  nom!: string
  products:Product[] = []
}

// With initial value for product

export class Category {
  idcategory!: number
  nom!: string
  products:Product[] = [{
    nom:'',
    prix:0
  }]
}
  • Related