我正在尝试在运行时使用ngx-formly动态设置表单字段:
app.component.html
<form [formGroup]="form" (ngSubmit)="submit(model)">
<formly-form [form]="form" [fields]="fields" [model]="model">
<button type="submit" class="btn btn-default">Submit</button>
</formly-form>
</form>
<button (click)="setFields()">Click Me To Dynamically Add Fields</button>
app.component.ts
import { Component } from '@angular/core';
import {FormGroup} from '@angular/forms';
import {FormlyFieldConfig} from '@ngx-formly/core';
import { ChangeDetectorRef } from '@angular/core';
import { ApplicationRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title: string;
form = new FormGroup({});
model = { email: 'email@gmail.com' };
fields: FormlyFieldConfig[] = [];
constructor(private appRef: ApplicationRef) {
}
setFields() {
this.fields.push({
key: 'email',
type: 'input',
templateOptions: {
type: 'email',
label: 'Email address',
placeholder: 'Enter email',
required: true,
}
});
//this.form.reset();
this.appRef.tick();
}
submit(model) {
console.log(model);
}
}
似乎该字段是动态添加的。但是,“必需”验证器似乎无法正常工作。有什么我想念的吗?
浏览器中的错误是:
ERROR TypeError: Unable to get property 'showError' of undefined or null reference
这有可能吗?