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

元气小坏坏 提交于 2019-12-11 05:59:28

问题


In angular 6, We have two approaches to create the form.

  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.

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. )


回答1:


Use ControlValueAccessor to Create Custom Form Controls in Angular

A ControlValueAccessor acts as a bridge between the Angular forms API and a native element in the DOM.

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!

Check this:https://alligator.io/angular/custom-form-control/

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



来源:https://stackoverflow.com/questions/51897650/how-to-add-validation-in-template-driven-form-from-component-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!