Setting the validity of a Angular 2 control from within a custom component
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.
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 });
}
});
this.myForm.controls['currentValue']....
but there is currently no way to explicitely set it to valid
or invalid
.
You can define a validator and change the criteria so it marks the control invalid.
See for example https://github.com/angular/angular/issues/4933
如何在任何formGroup上设置VALID或INVALID
// Where this.form === FormGroup;
// FormGroup can be deeply nested, just call at the level you want to update.
// That level should have direct access to base FormControls
// Can be done in a validator function;
this.form.get('name').setErrors({required: true});
// => this.form.get('name').invalid === true;
// Perhaps on Submit, click, event NOT in validator function
Object.entries(this.form.controls).forEach(([key, ctrl]) => {
ctrl.updateValueAndValidity();
});
// => this.form.get('name').invalid === false;
// => this.form.get('name').valid === true;
// => this.form.get('name').errors === null;
链接地址: http://www.djcxy.com/p/92096.html