我有以下型号。正如你所看到的,电子邮件需要一个字符串数组
export interface Member {
id: string;
name: string;
lastName: string;
emails: string[];
}
export type MemberPreview = Omit<Member, "id">;
此外,我还使用 formly 定义了以下表单配置
form = new FormGroup({});
model: MemberPreview = {
name: "",
lastName: "",
emails: [],
};
fields: FormlyFieldConfig[] = [
{
key: "name",
type: "input",
props: {
label: "Name",
required: true,
},
},
{
key: "lastName",
type: "input",
props: {
label: "Lastname",
required: true,
},
},
{
key: "emails",
type: "input",
props: {
label: "Emails",
required: true,
},
},
];
options: FormlyFormOptions = {};
模板:
<pre>{{ model | json }}</pre>
<hr />
<pre>{{ form.value | json }}</pre>
<form [formGroup]="form" (ngSubmit)="onSubmit()" autocomplete="off">
<formly-form
[form]="form"
[fields]="fields"
[model]="model"
[options]="options"
></formly-form>
<button type="submit">Submit</button>
</form>
模型初始状态
{
"name": "",
"lastName": "",
"emails": []
}
添加值后的模型
{
"name": "john",
"lastName": "doe",
"emails": "[email protected]"
}
我尝试的是,当在电子邮件中添加值时,该值位于数组内。
预期结果
{
"name": "john",
"lastName": "doe",
"emails": ["[email protected]"]
}
我怎样才能达到这个结果?预先感谢
更新0
我认为使用钩子可以近似预期的结果。我附上一个例子
{
key: "emails",
type: "input",
props: {
label: "Emails",
required: true,
},
hooks: {
onInit: (field: FormlyFieldConfig) => {
field.form?.get("emails")?.setValue(["abc"]);
},
onChanges: (field: FormlyFieldConfig) => {
field.form?.get("emails")?.setValue("[xml]");
},
},
},
我设法使用正式的钩子获得了预期的结果,如下
{
key: "emails",
type: "input",
props: {
label: "Emails",
required: true,
},
validators: {
validation: [emailValidator],
},
hooks: {
onInit: (field: FormlyFieldConfig) => {
field.form?.get("emails")?.valueChanges.subscribe({
next: (value) => {
this.model.emails = [value];
},
});
},
},
},
我已经确认验证有效
我不知道这是否是一个正确的解决方案。无论如何,我会附上一个完整的示例,以防相关。
form = new FormGroup({});
model: MemberPreview = {
name: "",
lastName: "",
emails: [],
};
fields: FormlyFieldConfig[] = [
{
key: "name",
type: "input",
props: {
label: "Name",
required: true,
},
},
{
key: "lastName",
type: "input",
props: {
label: "Lastname",
required: true,
},
},
{
key: "emails",
type: "input",
props: {
label: "Emails",
required: true,
},
validators: {
validation: [emailValidator],
},
hooks: {
onInit: (field: FormlyFieldConfig) => {
field.form?.get("emails")?.valueChanges.subscribe({
next: (value) => {
this.model.emails = [value];
},
});
},
},
},
];
options: FormlyFormOptions = {};