Почему мои переключатели не переключаются в динамически сгенерированной Реактивной Форме? - PullRequest
0 голосов
/ 23 октября 2019

Я видел кучу разных постов по использованию переключателей с динамически генерируемыми Реактивными формами, но пока ничего, что я изменил, не сработало. У меня проблема в том, что мои переключатели переключаются один раз, а затем я не могу переключать их снова. Они оба верны, что, как предполагается, невозможно, потому что они радио-кнопки. Моя форма имеет флажки, и они работают нормально. Я добавил, удалил и изменил атрибуты 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);

                }
            }
        }

1 Ответ

0 голосов
/ 23 октября 2019

В ваших радиокнопках отсутствует атрибут name, который группирует радиокнопки вместе. Атрибут name должен иметь одинаковое значение / быть общим для всех переключателей с группой.

После добавления атрибута name переключатели должны "отключаться" при нажатии другой кнопки. в той же группе.

Проверьте этот ответ, который имеет некоторые детали реализации: https://stackoverflow.com/a/49078441/1433107

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...