Angular ReactiveForm formControl counter

1.3k Views Asked by At

I try to build up a counter in Angular as a ReactiveForm to generate a JSON string which I want to send to another form to continue a purchase process.

My counter just working fine, but I don't get the value into the string without an input field. But I dont want to have there an input field for the user.

My code of the FormGroup looks like this at the moment:

<div formGroupName="ticket">
    <div class="row">
      <p>Adults</p>
      <i class="fa fa-minus-circle fa-2x" aria-hidden="true" (click)="decrementAdult();"></i>
      <p formControlName="valueAdult" ngDefaultControl>{{counterValueAdult}}</p>
      <i class="fa fa-plus-circle fa-2x" aria-hidden="true" (click)="incrementAdult();"></i>
    </div>
    <div> ... same for children ... </div>
  </div>

In the request.component.ts file I have a FormGroup:

requestForm = new FormGroup({
  foo1: new FormControl(),
  foo2: new FormControl(),
  ticket: new FormGroup({
    valueAdult: new FormControl(),
    valueChildren: new FormControl()
  })
});
incrementAdult() {
  this.counterValueAdult +=1;
  if (this.counterValueAdult >= this.maxAdult)
    this.counterValueAdult = 4;
    this.requestForm.get('ticket.valueAdult').setValue = this.counterValueAdult;
}
decrementAdult() {
  this.counterValueAdult -=1;
  if (this.counterValueAdult <= this.minAdult)
    this.counterValueAdult = 1;
    this.requestForm.get('ticket.valueAdult').setValue = this.counterValueAdult;
}

At the end of the form I catch the input for improvement with:

 <p>{{ requestForm.value | json }}</p>

and get back: { "foo1": value, "foo2": value, "ticket": { "valueAdult": null, "valueChildren": null } }

Does anyone have an idea to get back the value between the parenthesis instead of null?

<p ... >{{...}}</p>
2

There are 2 best solutions below

9
On

You just need to update the value of valueAdult with the calculated value in the methods where you increment/decrement.

incrementAdult(){
  // as before
   this.requestForm.get('ticket').get('valueAdult').setValue = this.counterValueAdult;
   // or  this.requestForm.get('ticket.valueAdult').setValue = this.counterValueAdult;
}

decrementAdult(){
  // as before
   this.requestForm.get('ticket').get('valueAdult').setValue = this.counterValueAdult;
}
1
On

you can use

ticket.get('valueAdult').value

Anyway, Why do you use a reactiveForm? You don't need it, just

@Component({
  selector: 'bla-bla',
  template: '<p>ticket.adults</p>'
})
export class HeroDetailComponent1 {
  ticket:any={"adults":3};
}