1

我已经使用 Angular 提供的 controlValueAccesor 接口创建了一个自定义表单控件组件。

现在我正在使用这样的自定义组件。

家长:

<custom-control [formControl]="customControl"></custom-control>

它工作正常,符合预期。当我尝试运行setErrors方法时出现问题,因为我希望错误传播到自定义组件,以便我可以显示从组件外部发送的错误。

custom-control在我这样做时使用的父组件中:

someValidation() {
  this.customControl.setErrors({
    myError: true
  })
}

在我的自定义控件组件的模板中,我可以看到这个

<form [formGroup]="form">
  <div> {{form.errors}} </div> <!-- I want to be able to propage 'myError' here -->
</form>

有什么建议么?

4

1 回答 1

0

我认为您可以像这样将当前FormControl实例注入您的custom-component(实现ControlValueAccessor)中:

// inside `custom-component`

get errors () {
  return this.ctrl.errors;
}

constructor (private ctrl: NgControl) { }

此解决方案基于指令的实施方式 FormControl

constructor(
      /* ... validators ... */
      @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
      /* ... */) {
    super();
    this._rawValidators = validators || [];
    this._rawAsyncValidators = asyncValidators || [];
    this.valueAccessor = selectValueAccessor(this, valueAccessors);
  }

如果您想了解更多关于 Angular Forms 的信息,我建议您查看A彻底探索 Angular Forms

于 2020-07-24T18:21:49.763 回答