Angular2-模板驱动的表单验证,用于子组件中的输入字段 [英] Angular2- Template driven form validation for input field in child component

查看:103
本文介绍了Angular2-模板驱动的表单验证,用于子组件中的输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力在我的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.

在插件中,如果您开始输入namestreet,它将同时在form和我的model object中更新.但是当您开始键入postcode时,它将仅在我的model objectnot 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提交为空,我希望forminvalid.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆