0

I am using form async validation with updatOn: 'blur' in my Angular7 application. stackblitz

in this situation, I need to check if the name is unique(async validation).

this.myForm.get('name').statusChanges.subscribe(status => {
    if (status === 'VALID') {
        // to save the name to database.
    } else {
        // to show some errors.
    }
});

question is, where to put this code?

Current way

I tried this,in child component

@Input()
set myForm(myForm: FormGroup) {
  this._myForm = myForm;
  this.myForm.get('name').statusChanges.subscribe(status => {    // to subscribe statusChanges here.
    if (status === 'VALID') {
        // to save the name to database.
    } else {
        // to show some errors.
    }
  });
}

get myForm() {
  return this._myForm;
}


_myForm: FormGroup

it worked. But I have at least 10 attributs to do form validation, this will add too many codes to this @Input() set myForm() {}, so I need to do this in another function.

So, I quit to subscribe statusChange in the @Input attribute. if not here, where should I do this?

And I can't subscribe statusChange in ngOnInit, cause value is undefined in ngOnInit.

Anyone helps me pls.

4

1 回答 1

1

我认为您可以directive在这种情况下使用 - 创建一个指令并添加必要的input字段

指示

@Directive({
  selector: '[dynamicValidation]'
})
export class DynamicValidationDirective {

  constructor(private control: NgControl) { }

  ngOnInit() {
    if (this.control && this.control!= undefined) {
      this.control.statusChanges.subscribe((status) => {
        // Your logic will go here
      });
    }       
  }
}

现在只需directive在特定的输入字段中添加

输入

<input [formControlName]="controlName"
                         type="text"
                         dynamicValidation        //Added the directive
                         class="form-control form-control-sm" />

现在所有输入字段都将被标记为订阅,并且当状态更改时,特定输入值将分别更新

希望这对您有所帮助-谢谢!

于 2019-12-02T09:33:29.783 回答