Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push on FormArray without FormBuilder on Angular 2

I have form array, I am having hard time solving this.

this is my current code

.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>

I am having hard time how to populate and also push. I cant find any tutorial.

EDIT

I want something like this on submit

{
    codeId: 123,
    name: "wew",
    stepTextarea: "",
    steps: ['asdjlkas','12312','12321']
}
like image 884
Storm Spirit Avatar asked May 08 '17 06:05

Storm Spirit


1 Answers

Since you want the steps to look like this on submit:

steps: ['asdjlkas','12312','12321']

you shouldn't use formGroup inside steps.

The build of the form should look like this:

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
    });
}

EDIT:

This would be the way your addProcedure would look like:

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()
}

And your template would look like this:

<div formArrayName="steps">
<h3>Steps: </h3>
<ol *ngFor="let step of item.get('steps').controls; index as i"> 
   <span>{{step.value}}</span>
</ol>


Original answer with solution of how to do FormArray:

addProcedure should look like this:

  addProcedure (e): void {
    const steps = <FormArray>this.item.get('steps');
    steps.push(this.fb.control())
  }

And your template for formarray should look something like this:

<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>
like image 149
AT82 Avatar answered Oct 09 '22 21:10

AT82