Michael Niño
Michael Niño

Reputation: 467

Angular 5: How can I iterate over form components and set value

I have an Angular 5 form (uses Angular Bootstrap 4) radio button group components. There are about 25 radio button groups each has 3 options: N/A, Secondary, Primary. I would like to allow N/A and Secondary for all radio button groups however only one radio button group may have Primary checked.

I'd like to have a click handler that intercepts any Primary check, iterates over all other radio button groups and sets them to Secondary if currently checked as Primary thereby leaving only on radio button group with a Primary option checked. How is this possible from within my click handler?

enter image description here

Upvotes: 0

Views: 141

Answers (1)

Chris White
Chris White

Reputation: 30089

You should just be able to add a (change) event listener to each group, to call a method in your component to iterate the form and update the values where the control currently has a value of primary.

A Sample plunkr / stackblitz would be appreciated showing where you're at and can also then be used as a basis for the answer. Minus that, here's a simple proof-of-concept

StackBlitz example:

Here's the main points:

HTML:

Add a change handler to the primary radio input to handle being selected

<form [formGroup]="formGroup">
  <div *ngFor="let x of [1, 2, 3]">
    <input type="radio" value="na" [formControlName]="x">N/A
    <input type="radio" value="secondary" [formControlName]="x"> Secondary
    <input type="radio" value="primary" [formControlName]="x" 
        (change)="doPrimaryClick(x)"> Primary
  </div>
</form>

TS Code:

In the handler, find all controls which are currently set to primary and reset them to secondary

doPrimaryClick(x) {
    // ignore the poor control names here
    [1, 2, 3].filter(i => i !== x)
      .forEach(i => {
        const control = this.formGroup.get(`${i}`);
        // current control is primary, so reset to secondary
        if (control.value === 'primary') {
          control.setValue('secondary');
        }
      })
  }

Upvotes: 1

Related Questions