使用keyvalue管道遍历Angular表单控件时ngIf判断disabled属性不存在的错误解决方法咨询
disabled Property with Angular's keyvalue Pipe Got it, let's break down the problem first and fix it. The core issue here is that you're iterating over item.value—which is just a plain JavaScript object holding the value snapshot of your form group—instead of the actual FormControl instances. The keyvalue pipe on item.value only returns key and value pairs, so it doesn't include form control properties like disabled.
Here are two straightforward solutions to resolve this:
Solution 1: Iterate Over Form Control Instances Directly
Instead of looping through the form group's value, loop through its controls property (which contains the real FormControl/FormGroup instances). You can use the keyvalue pipe directly on item.controls to get both the control name and the full control object:
<div [formGroupName]="x"> <!-- Iterate over the form group's controls instead of its value --> <div *ngFor="let ctrlEntry of item.controls | keyvalue"> Key: <b>{{ctrlEntry.key}}</b> and Value: <b>{{ctrlEntry.value.value}}</b> <!-- Now we can access the disabled property from the control instance --> <input *ngIf="!ctrlEntry.value.disabled" type="text" [formControlName]="ctrlEntry.key"> <button (click)="editMethod(ctrlEntry.value)" type="button">Edit</button> </div> </div>
Why this works:
item.controlsis an object where each key is the control name, and each value is the correspondingFormControlinstance.ctrlEntry.valuegives you the full control object, so you can access properties likedisabled,valid, or methods likesetValue()directly.
Solution 2: Use a Component Helper to Get Control Names
If you'd rather avoid using keyvalue on the controls object, create a helper method in your component to fetch the list of control names, then retrieve each control instance by name:
Step 1: Add the helper method to your component
getControlNames(formGroup: FormGroup): string[] { return Object.keys(formGroup.controls); }
Step 2: Update the template
<div [formGroupName]="x"> <div *ngFor="let controlName of getControlNames(item)"> <ng-container [formControlName]="controlName"> Key: <b>{{controlName}}</b> and Value: <b>{{item.get(controlName).value}}</b> <input *ngIf="!item.get(controlName).disabled" type="text"> <button (click)="editMethod(item.get(controlName))" type="button">Edit</button> </ng-container> </div> </div>
Quick Best Practice Note:
Instead of using string interpolation (formControlName="{{ctrl.key}}"), use property binding ([formControlName]="ctrl.key")—it's more efficient and follows Angular's recommended patterns.
内容的提问来源于stack exchange,提问作者eladr

