从自定义组件中设置 Angular 2 控件的有效性



我有一个自定义的 Ng2 组件 a 我正在使用模型驱动方法。

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

因此,在我的自定义组件中,我拥有所需的所有逻辑,但我找不到一种方法来获取对 ngControl 的引用以从我的自定义组件内部将其设置为有效或无效。

您可以查看此链接以获取工作示例: https://github.com/byavv/angular2-playground/tree/master/client/app/modules/forms_explore

一些关键方面:
您需要实现 ControValueAccessor。

export class Datepicker implements ControlValueAccessor {

在组件中注入 ngControl 并注册它:

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

在组件中,您应该有一个验证字段的表单,以便您可以订阅以发出正确的值或设置父 ngControl 表单的错误。

 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']....

但目前没有办法明确将其设置为 validinvalid .

您可以定义验证程序并更改条件,以便将控件标记为无效。

例如,请参阅 https://github.com/angular/angular/issues/4933

如何在任何表单上设置有效无效

// 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;

最新更新