动态加载数据时,如何为 Angular 中的数组分配默认值?

问题描述 投票:0回答:1

我有一个名为“习惯”的数组。像这样

我将其显示在带有单选按钮的表格中(是,否)。

 <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. 如何将默认值设置为“否”。
  2. 根据点击是或否,将值放入数组中。
angular typescript radio-button radio-group
1个回答
0
投票

首先创建一个地图来存储结果

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

您可以使用 FormControl() 设置复选框的默认值

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

然后监听 valueChanges oberbable 将结果存储在 Map 中

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

当然,您可以使用 FormBuilder 通过循环来完成此操作。 (但请记住以反应形式包装所有输入

<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)
        })
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.