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

Bre*_*ett 9 forms angular

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

<form [ngFormModel]="myForm" class="layout vertical relative">
    <my-custom-comp ngControl="currentValue"></my-custom-comp>
</form>
Run Code Online (Sandbox Code Playgroud)

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

Bre*_*ett 7

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

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

export class Datepicker implements ControlValueAccessor {
Run Code Online (Sandbox Code Playgroud)

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

constructor(private ngControl:NgControl)
ngControl.valueAccessor = this;
Run Code Online (Sandbox Code Playgroud)

在组件中,您应该有一个验证字段的表单,以便您可以订阅以发出正确的值或设置父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 });
        }
      });
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 0

this.myForm.controls['currentValue']....
Run Code Online (Sandbox Code Playgroud)

但目前还没有办法将其显式设置为validor invalid

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

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

  • 我已经实现了“ControlValueAccessor”,但我不知道在哪里或如何设置有效性 (2认同)