【发布时间】:2019-10-23 00:58:59
【问题描述】:
我看过很多关于使用单选按钮和动态生成的响应式表单的不同帖子,但到目前为止,我所做的任何更改都没有奏效。我遇到的问题是我的单选按钮一起切换一次,然后我无法再次切换它们。它们都是真的,这被认为是不可能的,因为它们是单选按钮。我的表单有复选框,它们工作正常。我已经添加、删除和更改了 name 和 value 属性,但它的响应仍然相同。如果我删除绑定,表单将无法正确呈现。
我做错了什么?下面是相关代码。
<section
class="table__row"
[formGroup]="contactPreferencesForm"
*ngFor="let preference of communicationPref.preferences">
<div class="table__row__question">
<p class="t-data t-bold">{{preference.display_text}}</p>
<p class="t-caption">{{preference.description}}</p>
</div>
<ng-container
*ngFor="let option of preference.options; let i = index">
<div
*ngIf="!preference.select_many; else oneOption"
class="table__cell">
<div class="u-maxXY u-flex u-justifyCenter">
<input
type="checkbox"
class="input input--checkbox"
ngDefaultControl
[formControl]="contactPreferencesForm.get(['communication', 'preferences']).controls[i]">
</div>
</div>
// radio buttons that aren't working
<ng-template #oneOption>
<div class="table__cell">
<div class="u-maxXY u-flex u-justifyCenter">
<input
type="radio"
class="input input--radio"
value="contactPreferencesForm.get(['communication', 'preferences']).controls[i]"
[formControl]="contactPreferencesForm.get(['communication', 'preferences']).controls[i]">
</div>
</div>
</ng-template>
</ng-container>
</section>
// 初始化表单
this.contactPreferencesForm = new FormGroup({});
this.memberService.initPreferences();
this.memberService.communicationPreferences.subscribe((val) => {
this.communicationPref = val[0];
this.contactPreferencesForm.addControl('communication', new FormGroup({}));
this.communicationPref['preferences'].forEach((preference) => {
const communication_preferences = this.contactPreferencesForm.get('communication') as FormGroup;
communication_preferences.addControl('preferences', new FormArray([]));
this.formControlArray = this.contactPreferencesForm.get(['communication', 'preferences']) as FormArray;
preference.options.forEach((option, i) => {
this.formControlArray.push(new FormControl(null));
if (!!option.name) {
this.allPreferences.push(option.name);
}
});
});
// 使用来自数据库的已保存响应填充表单 this.userPreferences = val[1];
// creating an arr of userPreferences to filter so I can match against the item's index in allPreferences
const userPreferencesArr = [];
this.userPreferences['data'].forEach((preference, i) => {
if (!!preference.name) {
userPreferencesArr.push(preference.name);
} else {
console.error('Your preferences must include a name key');
}
});
for (const i in this.allPreferences) {
if (this.allPreferences.hasOwnProperty(i)) {
const formValue = this.contactPreferencesForm.get(['communication', 'preferences']).value;
// returning the index of the userPreferences relative to all preferences
if (userPreferencesArr.indexOf(this.allPreferences[i]) > -1) {
// setting the index of the userPreference in the form
formValue[i] = true;
this.contactPreferencesForm.get(['communication', 'preferences'])
.patchValue(formValue);
}
}
}
【问题讨论】:
标签: angular forms typescript angular-reactive-forms