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

时间:2016-06-07 04:00:10

标签: forms angular

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

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

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

3 个答案:

答案 0 :(得分:7)

您可以查看此链接以获取有效工作示例: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 });
        }
      });

答案 1 :(得分:0)

this.myForm.controls['currentValue']....

但目前无法明确将其设置为validinvalid

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

参见例如https://github.com/angular/angular/issues/4933

答案 2 :(得分:0)

  

如何在任何formGroup上设置有效无效

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