Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1.2K
Vistas
¿Cómo puedo acceder a formArray de FormGroup en * ngFor en angular?

Estoy usando FormControl anidado usando FormArray. Mi formulario es así:

 let form = new FormGroup({ name: new FormControl(), email: new FormControl(), Addresses : new FormArray([ new FormGroup({ building: new FormControl(), society : new FormControl(), }), new FormGroup({ building: new FormControl(), society : new FormControl(), }) new FormGroup({ building: new FormControl(), society : new FormControl(), }) ]) }) addNewAddress() { let newAddress = new FormGroup({ building: new FormControl(), society : new FormControl(), }); this.form.get("addresses").push(newAddress) }

Y en plantilla HTML

 <div *ngFor="let controlGroup of form.get('addresses').controls; let i=index"> <ng-container [formGroup]="controlGroup"> <input type="text" formControlName="building" /> <input type="text" formControlName="society" /> </ng-container> </div>

** Pero el código anterior devuelve un Build Error como si los controles no existieran en abstractControl. **

Así que convierto form.get('addresses') en FormControl usando este getter Melthod.

 get addressArray() : FormArray { return form.get('addresses') as FormArray } //And use it in HTML like this <div *ngFor="let controlGroup of addressArray.controls; let i=index"> <ng-container [formGroup]="controlGroup"> <== now here is build error <input type="text" formControlName="building" /> <input type="text" formControlName="society" /> </ng-container> </div>

Después de esa Conversión. Se generó un nuevo error de compilación que controlGroup does not contain this methods : addControl, removeCotnrol and ...

Porque addressArray.**controls** devuelve una matriz de abstractControl en lugar de FormControl y la directiva [formGroup] necesita FormControl .

¿Cómo puedo definir Tipo en *ngFor así:

 let (controlGroup: FormControl) of addressArray.controls; let i=index

¿Es eso posible o no?

Por favor, ayúdame.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Puede usar eso con Type de la misma manera que usó como addressArray.controls

Aquí está el código completo:

 let form = new FormGroup({ name: new FormControl(), email: new FormControl(), Addresses : new FormArray([ new FormGroup({ building: new FormControl(), society : new FormControl(), }), new FormGroup({ building: new FormControl(), society : new FormControl(), }) new FormGroup({ building: new FormControl(), society : new FormControl(), }) ]) }) addNewAddress() { let newAddress = new FormGroup({ building: new FormControl(), society : new FormControl(), }); this.form.get("addresses").push(newAddress) } get addressArray() : FormArray { return form.get('addresses') as FormArray } get addressControlsArray() : FormGroup[] { return this.addressArray.controls as FormGroup[] }

En HTML

 <div *ngFor="let controlGroup of addressControlsArray; let i=index"> <ng-container [formGroup]="controlGroup"> <input type="text" [formControlName]="building" /> <input type="text" [formControlName]="society" /> </ng-container> </div>

Y puede iterar a través de todo formField para clear all it's validator esta manera:

 nestedFormFieldIterator(formGroup: FormGroup | FormArray, action: "ClearValidation" | "MarkAsDirty"): void { Object.keys(formGroup.controls).forEach(key => { const control = formGroup.controls[key] as FormControl | FormGroup | FormArray; if (control instanceof FormControl) { // console.log(`Clearing Validators of ${key}`); if (action == "ClearValidation") { control.clearValidators(); } if (action == "MarkAsDirty") { control.markAsDirty(); } control.updateValueAndValidity(); } else if (control instanceof FormGroup || control instanceof FormArray) { // console.log(`control '${key}' is nested group or array. calling clearValidators recursively`); this.nestedFormFieldIterator(control, action); } }); }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda