如何使用ngModel获取动态复选框的值?附问卷数据库结构
Alright, let's walk through how to use Angular's ngModel to capture values from those dynamic checkboxes based on your questionnaire data structure. Here's a practical, step-by-step implementation:
First, we'll define your questionnaire data in the component and set up a structure to track selected answers. Each question (identified by its prefix) will map to an array of selected option values.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-questionnaire', templateUrl: './questionnaire.component.html', styleUrls: ['./questionnaire.component.css'] }) export class QuestionnaireComponent implements OnInit { // Your questionnaire data from the database questionnaire = { "id": "5ac5f074867d190bc471dc59", "name": "Diabetes Questionnaire Test", "item": [ { "prefix": "1", "text": "Do you have family history of diabetes?", "Questiontype": "choice", "options": [ { "value": "Yes", "checked": false }, { "value": "No", "checked": false }, { "value": "I Don't know", "checked": false } ] }, { "prefix": "2", "text": "Are you hypertensive?", "Questiontype": "choice", "options": [ { "value": "Yes", "checked": false }, { "value": "No", "checked": false } ] } ] }; // Stores selected values: key = question prefix, value = array of selected options selectedAnswers: { [key: string]: string[] } = {}; ngOnInit() { // Initialize empty arrays for each choice-type question this.questionnaire.item.forEach(question => { if (question.Questiontype === 'choice') { this.selectedAnswers[question.prefix] = []; } }); } // Optional: Helper to log selected answers for debugging viewSelectedAnswers() { console.log('Current selected answers:', this.selectedAnswers); } }
Next, we'll loop through the questionnaire items and render checkboxes for each option. We'll use ngModel to two-way bind the checkboxes to our selectedAnswers structure.
<div class="questionnaire"> <h2>{{ questionnaire.name }}</h2> <!-- Loop through each question --> <div *ngFor="let question of questionnaire.item" class="question-block"> <p>{{ question.prefix }}. {{ question.text }}</p> <!-- Render checkboxes only for choice-type questions --> <div *ngIf="question.Questiontype === 'choice'" class="options"> <label *ngFor="let option of question.options" class="option"> <input type="checkbox" [value]="option.value" [(ngModel)]="selectedAnswers[question.prefix]" (change)="syncCheckedStatus(question.prefix, option.value, $event.target.checked)" /> {{ option.value }} </label> </div> </div> <!-- Button to view selected answers --> <button (click)="viewSelectedAnswers()">Show Selected Answers</button> </div>
checked Property (Optional) If you need to keep the original checked field in your database structure updated when a checkbox is toggled, add this helper method to the component:
syncCheckedStatus(questionPrefix: string, optionValue: string, isChecked: boolean) { // Find the target question const targetQuestion = this.questionnaire.item.find(q => q.prefix === questionPrefix); if (!targetQuestion) return; // Find the target option and update its checked status const targetOption = targetQuestion.options.find(opt => opt.value === optionValue); if (targetOption) { targetOption.checked = isChecked; } }
Don't forget to import FormsModule in your Angular module (this is required for ngModel to work):
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Required for ngModel import { AppComponent } from './app.component'; import { QuestionnaireComponent } from './questionnaire/questionnaire.component'; @NgModule({ declarations: [ AppComponent, QuestionnaireComponent ], imports: [ BrowserModule, FormsModule // Add this line ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
- Each checkbox is bound to the corresponding array in
selectedAnswersusing the question'sprefixas the key. - When a user checks/unchecks a box,
ngModelautomatically adds/removes the option's value from the array. - The optional
syncCheckedStatusmethod keeps your original data'scheckedfield in sync with the UI state, which is useful if you need to save the updated state back to the database.
内容的提问来源于stack exchange,提问作者Unah Henry

