@for not able to iterate formarray in angular 19

Discussão em 'Angular' iniciado por Sasi Kumar, Novembro 20, 2024.

  1. Sasi Kumar

    Sasi Kumar Guest

    i create one formgroup like this

    getUserInfoForm(data?: UserInfo) {

    return this.formBuilder.group({

    name: [data?.name ? data.name : null, [Validators.required]],

    age: [data?.age ? data.age : null, [Validators.required, Validators.min(18),Validators.max(99)]],

    gender: [data?.gender ? data.gender : null, [Validators.required]],

    hobbies: this.formBuilder.array([]),

    })

    }


    this is my ts

    ngOnInit() {

    this.userInfo = this.formsService.getUserInfoForm();

    this.addHobby();

    }

    getHobbies(): FormArray{

    return this.userInfo.get('hobbies') as FormArray;

    }

    addHobby(data?: string) {

    this.getHobbies().push(data ? new FormControl(data) : new FormControl(''))

    }

    removeHobby(index: number) {

    this.getHobbies().removeAt(index);

    }


    here i able to iterate hobbies list using *ngFor

    <div class="col-12 d-flex justify-content-between" formArrayName="hobbies">
    <label>Hobbies</label>
    <div *ngFor="let hobby of getHobbies().controls; let i = index" class="d-flex gap-5 justify-content-start w-50">
    <input class="form-control w-50" type="text" [formControlName]="i">
    <button type="button" class="btn btn-primary" >Add</button>
    <button type="button" class="btn btn-secondary" >Remove</button>
    </div>
    </div>


    but i cant able did this using @for()

    <div class="col-12 d-flex justify-content-between">
    <label>Hobbies</label>
    @for(hobby of getHobbies().controls; track $index) {
    <div class="d-flex gap-5 justify-content-start w-50">
    <input class="form-control w-50" type="text" name="hobby" formControlName="hobby">
    <button class="btn btn-primary">Add</button>
    <button class="btn btn-secondary">Remove</button>
    </div>
    }
    </div>


    facing below error

    Type Array<AbstractControl<any>> must have a [Symbol. iterator]() method that returns an iterator.

    enter image description here

    can't able to iterate formarray using @for in angular 19

    facing below error

    Type Array<AbstractControl<any>> must have a [Symbol. iterator]() method that returns an iterator.

    Continue reading...

Compartilhe esta Página