提问人:Damith Jayawardhane 提问时间:9/19/2023 最后编辑:Damith Jayawardhane 更新时间:9/19/2023 访问量:72
动态加载数据时,如何在 Angular 中为数组分配默认值?
How can I assign default values to an array in Angular when the data is loaded dynamically?
问:
我将其显示在带有单选按钮的表格中(是,否)。
<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>
- 如何将默认值设置为“否”。
答:
0赞
giacomoto
9/19/2023
#1
首先创建一个地图来存储结果
const results = new Map<number, boolean>();
您可以使用 FormControl() 设置复选框的默认值
const habitOne = new FormControl(false);
results['habitOne'].set(false);
然后监听 valueChanges obserbable 将结果存储在 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)
})
}
}
评论
0赞
Damith Jayawardhane
9/19/2023
this.policyService.getMasterData().subscribe((data2) => { let x = 0; data2.data.habits.forEach((element) => { this.lifeStyleFormGroup.addControl( "habitsSufferedMain" + x, new FormControl(false) );
我像这样创建了 FormControl。但未设置默认值
0赞
giacomoto
9/19/2023
拥有一个 stackbliz 会很有帮助
0赞
Damith Jayawardhane
9/19/2023
我创建了stackbliz
评论
this.policyService.getMasterData().subscribe((data2) => { let x = 0; data2.data.habits.forEach((element) => { this.lifeStyleFormGroup.addControl( "habitsSufferedMain" + x, new FormControl(false) );
<input type="radio" [value]="true">
<input type="radio" [value]="1">
[checked]="true"
[
]