You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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:

1. Component Setup

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);
  }
}
2. HTML Template with Dynamic Checkboxes

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>
3. Sync Original 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;
  }
}
4. Critical Setup: Import FormsModule

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 { }
How It Works
  • Each checkbox is bound to the corresponding array in selectedAnswers using the question's prefix as the key.
  • When a user checks/unchecks a box, ngModel automatically adds/removes the option's value from the array.
  • The optional syncCheckedStatus method keeps your original data's checked field 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:03:52