Angular 12中如何在下拉选择选项时隐藏当前及之前的问题
Hey there! I see you're working on an Angular 12 project with Form Arrays for a questionnaire, and you're stuck on removing previous and current questions when a jump option is selected. Let's work through this together—reactive forms can be a bit tricky at first, but we'll get it sorted.
First, Add the Selection Handler to Your Template
First up, we need to trigger a method whenever the user selects a jump option. Update your <select> element to include a (change) event binding:
<select name="jumpto" id="jumpto{{optIndex}}0" class="form-control" formControlName="jumpto" (change)="handleJumpSelection(ind, $event)"> <option value="" disabled></option> <ng-container *ngFor="let item of overallQuestionArray;let i=index;" > <option *ngIf="overallQuestionArray.length > 1" [value]="item.linkedId" [title]="item.question">Q{{i+1}}. {{item.question}}</option> </ng-container> </select>
I simplified the parameters since we don't strictly need the option index here—just the current question's index (ind) and the event object.
Implement the Handler in Your Component
Now add this method to your component class. The key here is to safely remove the current question and all previous ones from your Form Array. We'll remove elements from the current index backwards to avoid index shifting issues:
// Make sure this method is in your component handleJumpSelection(currentQuestionIndex: number, event: Event) { const selectedLinkedId = (event.target as HTMLSelectElement).value; // Exit if no option is selected if (!selectedLinkedId) return; // Get reference to your questions Form Array const questionsFormArray = this.questionData(); // Remove current question AND all previous ones (start from current index and go down) for (let i = currentQuestionIndex; i >= 0; i--) { questionsFormArray.removeAt(i); } // Optional: If you need to add the target jump question next, uncomment this section // const targetQuestion = this.overallQuestionArray.find(q => q.linkedId === selectedLinkedId); // if (targetQuestion) { // // Replace with your method to create a FormGroup for a question // questionsFormArray.push(this.createQuestionFormGroup(targetQuestion)); // } } // Double-check your questionData method returns the FormArray correctly questionData(): FormArray { return this.yourMainFormGroup.get('questions') as FormArray; } // Example of a helper method to create question FormGroups (adjust to your structure) createQuestionFormGroup(question: any): FormGroup { return this.fb.group({ question: [question.question], questionId: [question.questionId], type: [question.type], options: this.fb.array(question.options.map((opt: any) => this.fb.group({ option: [opt.option], jumpto: [opt.jumpto] }))) }); }
Key Notes to Avoid Issues
- Remove elements backwards: If we removed from index 0 upwards, each removal would shift the remaining elements' indexes, leading to skipping or deleting the wrong questions. Going from current index down to 0 fixes this.
- Type safety: We cast the event target to
HTMLSelectElementto safely access thevalueproperty—this keeps TypeScript happy. - Optional question addition: If you want to automatically load the target jump question after removing the previous ones, uncomment the optional section and adjust the
createQuestionFormGroupmethod to match your data structure.
Verify Your Form Structure
Make sure your main form group is properly initialized with the questions FormArray, like this:
yourMainFormGroup = this.fb.group({ questions: this.fb.array([]) });
That should do it! Test this out—when you select a jump option, the current question and all before it should be removed from the Form Array and the UI.
内容的提问来源于stack exchange,提问作者Adam Jose

