【发布时间】:2016-12-20 01:25:47
【问题描述】:
环境:Angular 2 RC 4,Typescript。
我有一个Dynamic Angular forms 的实现。我总共有 4 个字段 - 出生日期、电子邮件、问题和答案
问题:
dob: new TextboxQuestion({
key: 'dob',
label: 'Date of Birth',
value: '',
}),
email: new TextboxQuestion({
key: 'email',
label: 'Email Address',
value: '',
type: 'email',
}),
securityQuestion: new TextboxQuestion({
key: 'challengeQuestion',
label: 'Security Question',
value: '',
disabled: true
}),
securityAnswer: new TextboxQuestion({
key: 'challengeAnswer',
label: 'Write your answer',
value: '',
})
主/父组件的html的sn-p
<dynamic-form (responsesEvt)="onFormSubmitResponseReceived($event);" [sections]="sections" class="col-md-8"></dynamic-form>
动态表单组件
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<div *ngFor="let question of questions" class="form-row" >
<df-question [question]="question" [form]="form" *ngIf="!section.hidden"></df-question>
</div>
<div class="row">
<div class="col-md-5"></div>
<div class="col-md-7 btn-row">
<button type="submit" class="btn btn-primary pull-right" [disabled]="!form.valid">I agree with the Terms & Conditions</button>
<!--<button type="submit" class="btn btn-primary pull-right" [disabled]="!form.valid || subbmittedalready">I agree with the Terms & Conditions</button>-->
<button type="button" class="btn btn-default pull-right">Cancel</button>
</div>
</div>
</form>
df-question 组件
<div [formGroup]="form">
<div class="col-md-5"><label class="pull-right" [attr.for]="question.key"><span class="errorMessage">* </span>{{question.label}}</label></div>
<div class="col-md-7" [ngSwitch]="question.controlType">
<input *ngSwitchCase="'textbox'" [formControlName]="question.key" [id]="question.key" [type]="question.type" class="form-control"
[placeholder]="question.placeHolder"
/>
</div>
<div class="col-md-5"></div>
</div>
这是我的工作流程
Step 1 Initially at form load, only dob and email show up.
Step 2 User types in the dob and email. DOB and email are sent to the backend and if the info is correct, a "question" is returned.
Step 3 Now the question and answer fields appear (assuming that above step was successful). The question field is populated with the value returned from the server through the previous request
Step 4 User submits the form with dob, email, question and answer
关于如何使用动态表单实现这一点的任何想法?
我想我可以 不知何故在dob后抛出一个事件,电子邮件被填满,调用后端并得到问题。 使用变量隐藏/显示questnio并根据上述响应的成功/失败进行回答?
如果这是一个好方法,我怎么能感觉到用户已经填写了前两个字段并进行了后端调用。收到服务器回复后如何更新问题字段(特别是使用动态表单)?
如果没有,有更简单的方法吗?
【问题讨论】:
-
在我看来,您会创建两个单独的表单组。第一个表单组用于 dob 和电子邮件,第二个用于问答字段。最初,第二种形式是隐藏的(我会使用 ngIf)。验证第一个表单组后,取消隐藏第二个表单组并对其进行验证等
-
扩展@brando 您可以通过评估每个项目的 $error 对象的形式对第一组使用测试。如果所有
. .$error 对象为 null 或 undefined 或 0 长度,则验证已通过。使用stackoverflow.com/a/35614029/1586498的反义词
标签: javascript validation angular typescript forms