如何从 ControlValueAccessor 访问 NgControl

Bre*_*ett 1 angular

我正在构建一个自定义组件,它实现了 ControlValueAccessor,因此我可以在我的 from 中将它与 ngControl 和 ngModel 一起使用。现在,我希望验证组件在其内部的逻辑(以便它是自包含的)。到目前为止一切顺利,但现在我有一个循环依赖,因为我试图在一个组件中注入 NgControl(以设置外部表单状态),该组件自注入CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR提供程序。这里的代码:

const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR = new Provider(
  NG_VALUE_ACCESSOR, {
    useExisting: forwardRef(() => CustomInput),
    multi: true
  });

@Component({
  moduleId: module.id,
  selector: 'custom-input',
  templateUrl: 'custom-input.html',
  styleUrls: ['custom-input.css'],
  directives: [CORE_DIRECTIVES],
  providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class CustomInput implements ControlValueAccessor{

  private _text: any = '';
  public isValid:boolean = false;


  onChange: EventEmitter<any> = new EventEmitter();
  onTouched: any;


  constructor(private ngControl:NgControl) {

  }

  onToggle(){
    this.isValid = !this.isValid;
    let res = this.isValid? null:{ "test": true };
    this.ngControl.control.setErrors(res);
  }

  get text(): any { return this._text; };

  set text(v: any) {
    if (v !== this._text) {
      this._text = v;
      this.onChange.emit(v);
    }
  }

  writeValue(v) {
    this.text = v;
  }
  registerOnChange(fn): void {
    this.onChange.subscribe(fn);
  }
  registerOnTouched(fn): void {
    this.onTouched = fn;
  }

}
Run Code Online (Sandbox Code Playgroud)

如何从组件中获取对 ngControl 的引用?我知道您可以这样做: this.ngControl = this._injector.get(NgControl, null);但是在这种情况下,这种感觉就像是一种黑客攻击,不是吗?

Rob*_*zco 5

您可以注入NgControl您的组件。

constructor(@Self() @Optional() private ngControl: NgControl) {
    if (this.ngControl) {
      this.ngControl.valueAccessor = this;
    }
}
Run Code Online (Sandbox Code Playgroud)

并删除NG_VALUE_ACCESSOR提供程序。