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

使用keyvalue管道遍历Angular表单控件时ngIf判断disabled属性不存在的错误解决方法咨询

Solution for Accessing 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">
    &nbsp;<button (click)="editMethod(ctrlEntry.value)" type="button">Edit</button>
  </div>
</div>

Why this works:

  • item.controls is an object where each key is the control name, and each value is the corresponding FormControl instance.
  • ctrlEntry.value gives you the full control object, so you can access properties like disabled, valid, or methods like setValue() 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">
      &nbsp;<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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 10:57:41