Angular 10症状判断逻辑优化:复选框多选判定问题问询
Angular 10: Fixing COVID-19 Symptom Risk Assessment Logic
Why Your Current Implementation Isn't Working
Let's start by breaking down the core issues with your existing code:
- You're using the
choose1variable to store only the last symptom the user checked, not all selected symptoms. When the user picks the 4th symptom,choose1gets set tobody, so yourngSwitchimmediately triggers the positive result—completely ignoring any previously checked symptoms and the "more symptoms = higher risk" rule. - Having multiple separate
[ngSwitch]containers for results is redundant and creates logical chaos, since a single value can only match one case at a time.
A Better Approach: Track Selected Symptoms & Calculate Risk
We need to refactor the logic to track all selected symptoms, then use the count (or weighted risk) of those symptoms to determine the infection probability. Here's how to do it step by step:
Step 1: Update the Component Class (take-test.component.ts)
First, define your COVID-19 symptoms, add an array to track selected symptoms, and write a method to calculate risk based on how many symptoms are checked:
import { Component } from '@angular/core'; @Component({ selector: 'app-take-test', templateUrl: './take-test.component.html', styleUrls: ['./take-test.component.css'] }) export class TakeTestComponent { selectedDisease: string = ''; selectedSymptoms: string[] = []; // Define COVID-19 symptoms sorted by increasing risk covidSymptoms = [ { value: 'fever', label: 'Fever or chills' }, { value: 'cough', label: 'Cough' }, { value: 'short', label: 'Shortness of breath or difficulty breathing' }, { value: 'body', label: 'Muscle or body aches' } ]; // Set selected disease and reset symptoms on change setDisease(event: Event) { const target = event.target as HTMLInputElement; this.selectedDisease = target.value; this.selectedSymptoms = []; } // Add/remove symptom from selected list when checkbox toggles toggleSymptom(event: Event) { const target = event.target as HTMLInputElement; const symptomValue = target.value; if (target.checked) { this.selectedSymptoms.push(symptomValue); } else { const index = this.selectedSymptoms.indexOf(symptomValue); if (index !== -1) { this.selectedSymptoms.splice(index, 1); } } } // Calculate risk level based on number of selected symptoms getRiskResult(): string { const totalSymptoms = this.covidSymptoms.length; const selectedCount = this.selectedSymptoms.length; switch (true) { case selectedCount === 0: return 'no-symptoms'; case selectedCount === totalSymptoms: return 'positive'; case selectedCount >= 3: return 'high-risk'; case selectedCount >= 2: return 'medium-risk'; default: return 'low-risk'; } } }
Step 2: Refactor the Template (take-test.component.html)
Next, update the template to use the new logic, remove redundant ngSwitch containers, and show results based on the calculated risk:
<div class="container-fluid text-white bg-dark p-3"> <div class="row"> <div class="col-xs-12 col-lg-12 col-md-12">Hello [<i class='bx bx-plus-medical'></i><span style="color: red; font-weight: bolder;">RAHUL SINGH</span><i class='bx bx-plus-medical'></i>]</div> </div> </div> <div class="container mt-5"> <div class="jumbotron"> <h1 class="display-3">Hello, world!</h1> <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p> <hr class="my-4"> <p>It uses utility classes for typography and spacing to space content out within the larger container.</p> <p class="lead"> <a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a> </p> </div> </div> <!-- Select your Disease --> <div class="container"> <div class="row"> <div class="col-xs-6 col-md-6 col-lg-6"> <fieldset class="form-group"> <h3 class="font-weight-bold text-danger">Choose Your Disease</h3> <div class="form-check"> <label class="form-check-label h4 text-success font-weight-bold"> <input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios1" value="covid19" (change)="setDisease($event)"> [ COVID-19 ] </label> </div> <div class="form-check"> <label class="form-check-label"> <input type="radio" class="form-check-input" name="optionsRadios" id="optionsRadios2" value="two" (change)="setDisease($event)"> two </label> </div> </fieldset> </div> <div class="col-xs-6 col-md-6 col-lg-6"> <fieldset class="form-group" *ngIf="selectedDisease === 'covid19'"> <legend>Check Symptoms</legend> <div class="form-check" *ngFor="let symptom of covidSymptoms"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" [value]="symptom.value" (change)="toggleSymptom($event)"> {{ symptom.label }} </label> </div> </fieldset> <fieldset class="form-group" *ngIf="selectedDisease === 'two'"> <legend>Checkboxes</legend> <div class="form-check"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" value=""> Option two is selected </label> </div> </fieldset> </div> </div> </div> <!-- Final Result of Disease --> <div class="container mt-4" *ngIf="selectedDisease === 'covid19'"> <div class="row"> <div class="col-sm-12 col-md-12 col-lg-12" [ngSwitch]="getRiskResult()"> <!-- No symptoms --> <div *ngSwitchCase="'no-symptoms'"> <div class="list-group"> <a href="#" class="list-group-item list-group-item-action flex-column align-items-start active"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 h3 text-success">>>>>>>No symptoms detected.<<<<<<</h5> <small>Stay healthy!</small> </div> <p class="mb-1">Continue following basic hygiene practices to keep yourself safe.</p> </a> </div> </div> <!-- Low risk (1 symptom) --> <div *ngSwitchCase="'low-risk'"> <div class="list-group"> <a href="#" class="list-group-item list-group-item-action flex-column align-items-start active"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 h3 text-success">>>>>>>May be normal fever or flu.<<<<<<</h5> <small>Take precautions</small> </div> <p class="mb-1">Take paracetamol as needed and monitor your symptoms closely.</p> </a> <a href="#" class="list-group-item list-group-item-action flex-column align-items-start"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1">Rest at home and stay hydrated</h5> </div> <p class="mb-1">Building a Healthy Community One Individual at a Time.</p> </a> </div> </div> <!-- Medium risk (2 symptoms) --> <div *ngSwitchCase="'medium-risk'"> <div class="list-group"> <a href="#" class="list-group-item list-group-item-action flex-column align-items-start active"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 h3 text-warning">>>>>>>Self-quarantine and monitor symptoms closely.<<<<<<</h5> <small>Watch for worsening symptoms</small> </div> <p class="mb-1">Drink warm fluids, rest, and consider consulting a doctor if symptoms persist.</p> </a> </div> </div> <!-- High risk (3 symptoms) --> <div *ngSwitchCase="'high-risk'"> <div class="list-group"> <a href="#" class="list-group-item list-group-item-action flex-column align-items-start active"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 h3 text-danger">>>>>>>Must get a COVID-19 test.<<<<<<</h5> <small>Seek medical advice</small> </div> <p class="mb-1">Isolate yourself immediately and contact a healthcare provider for guidance.</p> </a> </div> </div> <!-- Positive (all symptoms) --> <div *ngSwitchCase="'positive'"> <div class="list-group"> <a href="#" class="list-group-item list-group-item-action flex-column align-items-start active"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1 h3 text-danger">>>>>>>You tested positive for COVID-19. Stay calm and follow medical advice.<<<<<<</h5> <small>Strict home isolation</small> </div> <p class="mb-1">Take prescribed medications, rest, and keep in touch with your healthcare provider.</p> </a> <a href="#" class="list-group-item list-group-item-action flex-column align-items-start"> <div class="d-flex w-100 justify-content-between"> <h5 class="mb-1">Stay hydrated and focus on recovery</h5> </div> <p class="mb-1">Building a Healthy Community One Individual at a Time.</p> </a> </div> </div> </div> </div> </div> <br><br> Thankyou
Key Improvements
- Tracks all selected symptoms: Uses an array instead of a single value, so we can count how many symptoms the user has checked.
- Risk-based logic: The
getRiskResult()method calculates risk based on the number of selected symptoms, perfectly aligning with your "more symptoms = higher risk" rule. - Cleaner template: Uses a single
ngSwitchcontainer for results, removing redundancy and making the logic easier to maintain. - Reset on disease change: Clears selected symptoms when the user switches diseases to avoid incorrect results.
内容的提问来源于stack exchange,提问作者user14109979
相关产品推荐
相关产品推荐

