迭代模板中的 FormControl 错误

Iterate FormControl Errors in template

我试图在 Angular FormControl 上显示所有错误,但我无法使用 ngFor 遍历错误对象,因为它不是数组

<ion-item>
    <ion-label>{{property.label}}
        <div class="error-message">
            <ul>
                <li *ngFor="let err of surveyForm.controls[property.label].errors">
                    {{ err}}
                </li>
            </ul>
        </div>
    </ion-label>
    <ion-input [formControlName]="property.label">
    </ion-input>
 </ion-item>

"Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays"

如何遍历 errors 这样的对象?

您可以创建一个 Pipe 将您的对象转换为对象键数组

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'objToKeys'
})
export class ObjToKeysPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (!value) {
      return value;
    }
    return Object.keys(value);
  }
}

然后像这样使用这个管道:

<ion-item>
    <ion-label>{{property.label}}
        <div class="error-message">
            <ul>
                <li *ngFor="let key of surveyForm.controls[property.label].errors | objToKeys">
                    {{ surveyForm.controls[property.label].errors[key] }}
                </li>
            </ul>
        </div>
    </ion-label>
    <ion-input [formControlName]="property.label">
    </ion-input>
 </ion-item>