Angular2-模板驱动的表单验证,用于子组件中的输入字段 [英] Angular2- Template driven form validation for input field in child component
问题描述
我一直在努力在我的angular2应用中添加template driven form validation
.
I was struggling with adding template driven form validation
in my angular2 app.
我分叉了 https://plnkr.co/edit/phhe74kAUmNZgNSmcsvm?p =预览
我无法单独完成custom component
的表单验证,并且其他html组件运行正常.
i failed to achieve the form validation for my custom component
alone and other html components are working fine.
在插件中,如果您开始输入name
和street
,它将同时在form
和我的model object
中更新.但是当您开始键入postcode
时,它将仅在我的model object
和not with form
中更新.
In the plunker, if you start typing name
and street
it will updated in both form
and and my model object
as well. but the when you start typing postcode
it will update only in my model object
and not with form
.
如果我将postcode
提交为空,我希望form
为invalid
.
I wanted the form
to be invalid
if i make postcode
filed to empty.
我在这里错过了什么吗?
Is i missed something here ?
推荐答案
当前,您的表单无法将您的子组件的输入字段识别为表单字段,因此您需要对子标签进行一些更改... name
属性和ngModel
将此子组件绑定到表单.在此处还包括required
.
Currently, your form doesn't recognize your child components' input field as a form field, you need to change your child tag a bit... to have the name
attribute and ngModel
to bind this child component to the form. Also include required
here.
最后,您需要添加ngDefaultControl
才能对表单字段进行双向绑定.因此,您的孩子标签在父母中应该看起来像这样:
Lastly, you need to add ngDefaultControl
to have two-way binding for the form field. So your child tag should look like this in your parent:
<my-input name="postcode" ngModel ngDefaultControl required [(value)]="user.address.postcode"></my-input>
这是你的分叉
这篇关于Angular2-模板驱动的表单验证,用于子组件中的输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!