简体   繁体   English

如何从 angular 6 的组件在模板驱动的表单中添加验证

[英]How to add validation in template driven form from component in angular 6

In angular 6, We have two approaches to create the form.在 angular 6 中,我们有两种方法来创建表单。

  1. Model-driven模型驱动
  2. Template-driven模板驱动

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.在模板驱动的方法中,我们通过模板本身中的指令和 HTML5 属性定义验证器。

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)" /> 

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. )这里,在ValueChangeEvent方法中,我需要更改我的文本框的验证。(例如,当用户输入内容时,我只需要在文本框中添加最小值验证。)

Use ControlValueAccessor to Create Custom Form Controls in Angular使用 ControlValueAccessor 在 Angular 中创建自定义表单控件

A ControlValueAccessor acts as a bridge between the Angular forms API and a native element in the DOM. ControlValueAccessor 充当 Angular 表单 API 和 DOM 中的原生元素之间的桥梁。

When creating forms in Angular, sometimes you want to have an input that isn't a standard text input, select, or checkbox.在 Angular 中创建表单时,有时您希望输入不是标准文本输入、选择或复选框。 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!通过实现 ControlValueAccessor 接口并将组件注册为 NG_VALUE_ACCESSOR,您可以将自定义表单控件无缝集成到模板驱动或响应式表单中,就像它是本机输入一样!

Check this: https://alligator.io/angular/custom-form-control/检查这个: https : //alligator.io/angular/custom-form-control/

Example for customFormValidation: https://stackblitz.com/edit/angular-hhgkje customFormValidation 示例: https ://stackblitz.com/edit/angular-hhgkje

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM