【发布时间】:2018-08-18 21:51:15
【问题描述】:
我有一个带有表单的 Angular 应用程序。我有一个输入字段,用户可以在其中输入一个字符串并单击一个添加按钮,然后解析输入,验证它,并将其添加到表单的模型中。输入元素的 [(ngModel)] 绑定到组件上的 transient variable 属性。验证成功后,瞬态变量的值将被清除,因此用户可以输入另一个要添加到模型中的项目。
瞬态变量的输入字段是必填字段,因为如果您从未向模型添加新项目,则无法提交表单。
我想更改输入元素的有效条件,这样当模型中至少有一个新项目被添加时,输入元素字段可以留空,我可以成功提交表单.
form.component.ts:
import { Component, OnInit } from '@angular/core';
import { Model } from './model';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
model: Model;
transientItem: string;
constructor() { }
get diagnostic() { return JSON.stringify(this.model); }
ngOnInit() {
this.model = new Model([]);
}
onSubmit() {
//handle submit logic
}
addItem() {
const items = this.transientItem.split(' ');
if (items.length === 3) {
const newItem = {
itemName: items[0],
itemValue: items[1],
itemLabel: items[2]
};
this.model.items.push(newItem);
this.transientItem = '';
} else {
alert('invalid item format');
}
}
}
form.component.html:
<form (ngSubmit)="onSubmit()" #myForm="ngForm">
{{diagnostic}}
<div class="form-group">
<input type="text" class="form-control" required [(ngModel)]="transientItem" name="item" #item="ngModel" />
<button type="button" (click)="addItem()">Add</button>
</div>
<button type="submit" [disabled]="!myForm.form.valid">Submit</button>
</form>
model.ts:
export class Model {
constructor(
public items: {
itemName: string,
itemValue: string,
itemLabel: string
}[]
) { }
}
当前行为:如果输入的值为空,则提交按钮被禁用,但只要我在文本字段中输入内容,我就可以提交表单...
预期行为:只有当我的模型的 items 属性中至少有 1 个项目时,我才能提交表单。如果我在模型中有 1 个项目,并且我将输入字段留空,我仍然可以提交表单,因为已经添加了一个项目。
【问题讨论】:
标签: angular angular-forms