Angular中基于所有数字输入框状态禁用切换按钮的问题
Looks like the issue here is that your current onChange method only checks the value of the input that triggered the event, not all the numeric inputs in the form. That's why clearing one input immediately enables the toggle, even if others still have values. Here's how to fix this:
Step 1: Update the Toggle State Check Logic
Instead of tracking a single input's value, we need to check all numeric input values bound to your numero array. We'll use Array.some() to detect if any input has a non-empty value, then set the toggle's enabled state accordingly.
First, refactor your TypeScript code to encapsulate the check into a reusable method, and update the event handler:
// Add this method to check all input values checkToggleEnabled(): void { // Check if ANY input in the numero array has a non-empty/non-null value const hasFilledInput = this.numero.some(value => value !== '' && value != null && value !== undefined ); // Enable toggle ONLY if NO inputs have values this.toggleEnabled = !hasFilledInput; } onChange(event): void { // Recheck state whenever any input changes this.checkToggleEnabled(); } // Optional: Initialize state when component loads ngOnInit(): void { this.checkToggleEnabled(); }
Step 2: Use Real-Time Input Event (Optional but Recommended)
Your current code uses the (change) event, which only triggers when the input loses focus. For a better user experience, switch to (input) so the toggle state updates as the user types:
<input [readonly]="!readOnlyUserForm || readOnlySpecificUserForm" type="number" (input)="onChange($event)" <!-- Replace (change) with (input) --> [required]=" isNE ? false : isNF ? false : arrayFormElements[i].mandatory == 'yes' " *ngIf="(arrayFormElements[i].type=='real' || arrayFormElements[i].type=='integer') && arrayFormElements[i].defaultvalue.length === 0 && arrayFormElements[i].name != 'Is_Dato_Mancante'" [attr.maxlength]="numeroMax[i]" [attr.minlength]="numeroMin[i]" [(ngModel)]="numero[i]" placeholder="Input" class="form-control" formControlName="valoreUtente">
How This Works
Array.some()iterates through every value in thenumeroarray. If even one value is not empty, null, or undefined, it returnstrue.- We set
toggleEnabledto the opposite of that result: if there's any filled input,toggleEnabledbecomesfalse(disabling the switches), and if all inputs are empty, it becomestrue(enabling the switches). - The reusable
checkToggleEnabledmethod ensures we can run this check not just on input changes, but also when the component initializes or when your dynamic form elements are loaded/updated.
Edge Cases Handled
- Empty strings (
'') - Null values
- Undefined values
- Dynamic addition/removal of inputs (as long as the
numeroarray stays in sync with the form elements)
内容的提问来源于stack exchange,提问作者Dev

