簡體   English   中英

如何正式修復angular中的“無法讀取未定義的屬性'選項'”?

[英]How to fix “Cannot read property 'options' of undefined” in angular formly?

我正在嘗試在 Angular 9 中為一些動態配置的 forms 使用 Formly。 它在 angular 8 上運行良好,但是當我將項目升級到 angular 9 時,出現以下錯誤。 錯誤

我的組件 class:

 export class CityFormComponent implements OnInit { editingCity?: City; loading: boolean; form = new FormGroup({}); model = {}; fields: FormlyFieldConfig[]; constructor( private store: Store<fromApp.AppState>, public dialogRef: MatDialogRef<CityFormComponent>, @Inject(MAT_DIALOG_DATA) public data: { id?: number, modelForm: any, }) { } ngOnInit() { if (this.data.modelForm) { this.fields = this.data.modelForm.fields; // console.log(this.fields); } if (this.data.id) { this.store.dispatch(new CityEditing(this.data.id)); } else { this.store.dispatch(new CityCreating()); } this.store.select('cities').subscribe(state => { this.loading = state.loading; if (state.selectedCityId > 0) { this.editingCity = state.cities.find(loc => loc.id === state.selectedCityId); } else { this.editingCity = {}; } }); } //... }
 <form [formGroup]="form" (ngSubmit)="submit()"> <formly-form [form]="form" [model]="editingCity" [fields]="fields"></formly-form> <button type="submit" [disabled]=".form.valid" mat-raised-button color="primary">Save</button> </form>

在這里你可以看到,我有我的fields: FormlyFieldConfig[] (我從后端獲取此表單配置),它看起來像正常的 FormlyFieldConfig[]:

fields: [
0: {
className: ""
defaultValue: null
key: "name"
templateOptions: {label: "Название", placeholder: "", description: "", required: true, options: []}
description: ""
label: "Название"
options: []
placeholder: ""
required: true
type: "input"
validation: {messages: []}
messages: [],
},
]

同時,如果我通過添加硬編碼字段屬性

this.fields = [
      {
        key: 'firstname',
        type: 'input',
      },
    ];

在 ngOnInit() 結束時,它會正常工作。

有沒有人知道如何解決它?

問題在於您的數據格式來自 API。 它包含帶有對象數組的 0 鍵。 它應該采用以下格式。

    fields: [
     {
    className: ""
    defaultValue: null
    key: "name"
    templateOptions: {label: "Название", placeholder: "", description: "", required: true, options: []}
    description: ""
    label: "Название"
    options: []
    placeholder: ""
    required: true
    type: "input"
    validation: {messages: []}
    messages: [],
    }
    ]

You can still modify this array in the correct format using filter.
Ex-   const flattenFields = fields.filter(res=>{
            if(typeof res =='object'){
                return res;
            }
        }); 

這應該可以解決您的問題!

這是我修復它的方法。

.html:

<formly-form #formlyForm [form]="form" [fields]="fields" [model]="model"></formly-form>

.ts:

form = new FormGroup({});

@ViewChild("formlyForm", { static: true })
formlyForm: FormlyForm;

resetForm() {
  this.form = new FormGroup({});
  if (this.formlyForm) {
    this.formlyForm.options.resetModel({});
  }
}

希望它對其他人也有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM