typescript - Cómo agregar elementos a FormArray sin FormBuilder en Angular 2
Tengo un arreglo de formularios, me está costando mucho resolver esto.
este es mi código actual
.ts
ngOnInit() {
this.item = this.fb.group({
codeId: ['', Validators.pattern(/^\d+$/)],
name: ['', [Validators.required, Validators.minLength(3)]],
stepTextarea: ['', []],
steps: [this.fb.array([]), []]
});
}
addProcedure (e): void {
e.preventDefault();
const control = <FormGroup>this.item;
const steps = <FormArray>this.item.controls['steps'];
steps.push(control.get('stepTextarea').value);
control.get('stepTextarea').setValue("", {onlySelf: true})
}
onSubmit({value, valid}: {value: Item, valid: boolean}): void {
const control = <FormGroup>this.item;
console.log(value);
}
.html
<ol ngFor [ngForOf]="item.get('steps').controls">
<span [formGroupName]="i">{{i}}</span>
</ol>
Estoy teniendo dificultades sobre cómo rellenar y también empujar. No puedo encontrar ningún tutorial.
EDITAR
Quiero algo así al enviar
{
codeId: 123,
name: "wew",
stepTextarea: "",
steps: ['asdjlkas','12312','12321']
}
Respuesta #1
Ya que quieres que los pasos se vean así al enviar:
steps: ['asdjlkas','12312','12321']
no deberías usar formGroup dentro de los pasos.
La construcción del formulario debería verse así:
ngOnInit() {
this.item = this.fb.group({
codeId: ['', Validators.pattern(/^\d+$/)],
name: ['', [Validators.required, Validators.minLength(3)]],
stepTextarea: [''],
steps: this.fb.array([]) // do not enclose steps inside an array
});
}
EDITAR:
Así es como se vería tu addProcedure:
addStep() {
const control = <FormArray>this.item.get('steps');
// push the value from stepTextArea to array
control.push(this.fb.control(this.item.get('stepTextArea').value))
// reset
this.item.get('stepTextArea').reset()
}
Y tu plantilla se vería así:
<div formArrayName="steps">
<h3>Steps: </h3>
<ol *ngFor="let step of item.get('steps').controls; index as i">
<span>{{step.value}}</span>
</ol>
Respuesta original con solución de cómo hacer FormArray:
Debería verse así addProcedure:
addProcedure (e): void {
const steps = <FormArray>this.item.get('steps');
steps.push(this.fb.control())
}
Y su plantilla para formarray debería verse algo así:
<div formArrayName="steps">
<div *ngFor="let step of item.controls.steps.controls; let i = index" >
<label>Step {{i+1}} </label>
<input [formControlName]="i" />
</div>
</div>
