如何从angular 6中的组件以模板驱动的形式添加验证 [英] How to add validation in template driven form from component in angular 6
问题描述
在角度6中,我们有两种创建表单的方法.
In angular 6, We have two approaches to create the form.
- 模型驱动
- 模板驱动
在模型驱动的方法中,我们通过组件中的代码定义了验证器.和 在模板驱动的方法中,我们通过指令和模板本身中的HTML5属性来定义验证器.
In the model-driven approach, we defined the validators via code in the component. And In the template-driven approach, we define the validators via directives and HTML5 attributes in our template itself.
有没有办法,在模板驱动的形式中,我们可以从组件代码定义验证.
Is there any approach, In the template-driven form, We can define the validation from component code.
在一些输入测试更改中,我需要从组件代码定义和更改文本框的验证.
I need to define and change the validation of a text box from component code on some input test change.
<input type="text" [(ngModel)]="value" (input)="ValueChangeEvent(myvalue)" />
在这里,在ValueChangeEvent
方法中,我需要更改文本框的验证.(例如,当用户键入内容时,只需要在文本框中添加最小值验证即可.)
Here, in the ValueChangeEvent
method, I need to change the validation of my textbox.(For example, when user type something, then only I need to add the minimum value validation in the text box. )
推荐答案
使用ControlValueAccessor在Angular中创建自定义窗体控件
Use ControlValueAccessor to Create Custom Form Controls in Angular
ControlValueAccessor充当Angular表单API之间的桥梁 和DOM中的本机元素.
A ControlValueAccessor acts as a bridge between the Angular forms API and a native element in the DOM.
在Angular中创建表单时,有时您希望输入的内容不是标准的文本输入,选择或复选框.通过实现ControlValueAccessor接口并将组件注册为NG_VALUE_ACCESSOR,您可以将自定义表单控件无缝地集成到模板驱动或反应形式中,就像它是本机输入一样!
When creating forms in Angular, sometimes you want to have an input that isn’t a standard text input, select, or checkbox. By implementing the ControlValueAccessor interface and registering the component as a NG_VALUE_ACCESSOR, you can integrate your custom form control seamlessly into template driven or reactive forms just as if it were a native input!
检查以下内容: https://alligator.io/angular/custom-form-control/
customFormValidation的示例: https://stackblitz.com/edit/angular-hhgkje
Example for customFormValidation:https://stackblitz.com/edit/angular-hhgkje
这篇关于如何从angular 6中的组件以模板驱动的形式添加验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!