角度组件作为自我验证的formControls

时间:2018-03-09 18:09:09

标签: javascript angular forms angular-reactive-forms

我不确定是否有更好的方法可以做到这一点,我认为应该有。基本上我有一个我想要作为独立表单控件处理的组件。此控件将始终附加某种特殊验证,并且我希望每当使用该组件时它都会冒泡到表单。

我已附上plunker。如果组件/ formControl无效,是否有办法将表单标记为无效?我知道我可以将验证器添加到表单本身,但我希望为将来使用此组件使事情变得简单和可预测。我也愿意接受更好的想法。

@Component({
  selector: 'my-app',
  template: `
    <form [formGroup]="form">
      <my-component-control formControlName="myComponent"></my-component-control>
    </form>
    <div>Form Value: {{form.value | json}}</div>
    <div>Form Valid: {{form.valid}}</div>
  `,
})
export class App {
  constructor(fb: FormBuilder) {
    this.form = fb.group({
      myComponent: ''
    });
  }
}

@Component({
  selector: 'my-component-control',
  template: `
    <div>Control Errors: {{control.errors | json}}</div>
    <input [formControl]="control">
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: forwardRef(() => MyComponentComponent),
    }
  ]
})
export class MyComponentComponent implements ControlValueAccessor {
  control: FormControl;

  onChange: any = () => { };
  onTouched: any = () => { };

  constructor() {
    this.control = new FormControl('', (control) => {
      return control.value ? null : {shouldHaveSomething: true};
    });
    this.control.valueChanges.subscribe((value) => {
      this.onChange(value);
      this.onTouched();
    });
  }

  writeValue (obj: any): void {
    this.control.setValue(obj);
  }
  registerOnChange (fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched (fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    throw new Error('Method not implemented.');
  }
}

1 个答案:

答案 0 :(得分:2)

一种解决方案可能是在主机AbstractControl

上使用setValidators方法

为此,我将通过AbstractControl引用NgControl。我们不能在构造函数中注入NgControl,因为我们会遇到实例化循环依赖的问题。

constructor(private injector: Injector) {
  ...     
}

ngOnInit() {
  Promise.resolve().then(() => {
    const hostControl = this.injector.get(NgControl, null);
    if (hostControl) {
      hostControl.control.setValidators(this.control.validator);
      hostControl.control.updateValueAndValidity();
    }
  }); 
}

<强> Ng-run Example