1

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

Nimish goel
  • 2,561
  • 6
  • 27
  • 42

1 Answers1

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

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
  • yeah, I got that, We can go with the custom form control, But how can we add the validations in that from component file. As per my understanding, We should write something in the onTouched() function of control, I have registered that event, But that is not getting the call. – Nimish goel Aug 18 '18 at 11:03
  • 1
    check this:https://stackoverflow.com/questions/44731894/get-access-to-formcontrol-from-the-custom-form-component-in-angular – Chellappan வ Aug 18 '18 at 11:25