How can I assign default values to an array in Angular when the data is loaded dynamically?

214 Views Asked by At

I have an Array called 'habits'. like this enter image description here

I show it in a table with radio buttons (yes, no).

enter image description here

 <tr *ngFor="let habits of masterDate.data.habits; index as x">
    <th class="tbl-border-right-bottom text-wrap" style="width: 50%">
        {{ habits.name }}
        <div hidden="true">
            <input type="text" formControlName="habitsSufferedMainId{{ x }}" />
        </div>
    </th>
    <td class="tbl-border-right-bottom">
        <div class="col-md-6">
            <div class="form-group d-flex justify-content-around pr-2">
                <div class="custom-control custom-radio">
                    <input type="radio" class="custom-control-input" id="habitsSufferedMain{{ x }}" value="1" name="habitsSufferedMain{{ x }}" formControlName="habitsSufferedMain{{ x }}" />
                    <label class="custom-control-label" for="habitsSufferedMain{{ x }}">Yes</label>
                </div>
                <div class="custom-control custom-radio">
                    <input type="radio" class="custom-control-input" id="isMainHabitNo{{ x }}" value="0" name="habitsSufferedMain{{ x }}" formControlName="habitsSufferedMain{{ x }}" [checked]="true" />
                    <label class="custom-control-label" for="isMainHabitNo{{ x }}">No</label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <textarea placeholder="If 'Yes' please give details" class="form-control form-control-sm" rows="2" formControlName="habitsSufferedMainReason{{ x }}"></textarea>
        </div>
    </td>
 </tr>
  1. How to set the default value to "No".
1

There are 1 best solutions below

3
giacomoto On

First create a map to store the results

const results = new Map<number, boolean>();

You can set the default value of the checkbox using the FormControl()

 const habitOne = new FormControl(false);
 results['habitOne'].set(false);

Then listen to the valueChanges obserbable to store the result in a Map

habitOne.valueChanges.subscribe(value => {
    results.set('habitOne', value)
})

Of course you can do this with a loop using the FormBuilder. (But remeber to wrap all the inputs in a reactive form <form [formGroup]=form>

form: FormGroup;

constructor(private fb: FormBuilder) {
    this.form = this.fb.group(
      this.habits.reduce((controls, habit, index) => {
        this.results.set(index, false)
        return {
        ...controls,
        [`habit${index}`]: new FormControl(false)
      }
    }, {}));

    Object.keys(this.form.controls).forEach((control, index) => {
        control.valueChanges.subscribe(value => {
            this.results.set(index, value == true)
        })
    }
  }