Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the validity of a Angular 2 control from within a custom component

Tags:

forms

angular

I have a custom Ng2 component a I am using the Model-Driven approach.

<form [ngFormModel]="myForm" class="layout vertical relative">
    <my-custom-comp ngControl="currentValue"></my-custom-comp>
</form>

So inside my custom component I have all the logic I need but I can't find a way to get a reference to the ngControl to set it to valid or invalid from inside my custom component.

like image 540
Brett Avatar asked Jun 07 '16 04:06

Brett


People also ask

Which form needs custom validator directive that wrap validation function for form validation?

Reactive forms define custom validators as functions that receive a control to validate. Template-driven forms are tied to template directives, and must provide custom validator directives that wrap validation functions.

What is Abstractcontrol in Angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.


1 Answers

You can check this link for a working example: https://github.com/byavv/angular2-playground/tree/master/client/app/modules/forms_explore

Some key aspects:
You need to implement ControValueAccessor.

export class Datepicker implements ControlValueAccessor {

Inject in your component the ngControl and register it:

constructor(private ngControl:NgControl)
ngControl.valueAccessor = this;

From within your component you should have a form that validates the field so you can subscribe to emit the correct value or set the error of the parent ngControl form.

 this.dateForm = builder.group({
          dateControl: ['', Validators.compose([Validators.required, CustomValidators.frenchDate])],
        });

    this.dateForm.valueChanges
      .subscribe((val) => {
        if (this.dateForm.valid) {
          this.onChange.emit(this.dateToTimestamp(val.dateControl));
        } else {
          this.ngControl.control.setErrors({ "wrongDate": true });
        }
      });
like image 103
Brett Avatar answered Oct 21 '22 18:10

Brett