Development Tip

누구든지 Angular2에서 양식 유효성 검사기를 트리거하는 방법을 알고 있습니까?

yourdevel 2020. 11. 24. 19:58
반응형

누구든지 Angular2에서 양식 유효성 검사기를 트리거하는 방법을 알고 있습니까?


angular2에서 다른 컨트롤이 변경 될 때 일부 컨트롤에 대해 Validator를 트리거하고 싶습니다. 양식을 재 검증하도록 지시 할 수있는 방법이 있습니까? 더 나은 방법은 특정 필드의 유효성 검사를 요청할 수 있습니까?

예 : 체크 박스 X와 입력 P가 주어집니다. 입력 P에는 X의 모델 값에 따라 다르게 작동하는 유효성 검사기가 있습니다. X가 선택 / 선택 취소되면 P에서 유효성 검사기를 호출해야합니다. P의 유효성 검사기는 모델에서 다음을 확인합니다. X의 상태를 결정하고 그에 따라 P의 유효성을 검사합니다.

다음은 몇 가지 코드입니다.

constructor(builder: FormBuilder) {
    this.formData = { num: '', checkbox: false };

    this.formGp = builder.group({
        numberFld: [this.formData.num, myValidators.numericRange],
        checkboxFld: [this.formData.checkbox],
    });
}

this.formGp.controls['checkboxFld'].valueChanges.observer({
    next: (value) => {
        // I want to be able to do something like the following line:
        this.formGp.controls['numberFld'].validator(this.formGp.controls['numberFld']);
    }
});

아무도 해결책이 있습니까? 감사!


여전히 답변을 찾고 있는지 모르겠으므로 여기에 제 제안이 있습니다.

이것 좀 봐 : Angular 2-AbstractControl

당신이 할 수있는 일은 다음과 같습니다.

this.formGp.controls['checkboxFld'].valueChanges.observer({
    next: (value) => {
       this.formGp.controls['numberFld'].updateValueAndValidity();
    }
});

이것은 유효성 검사기를 트리거하고 실행해야합니다. 또한 상태도 업데이트됩니다. 이제 유효성 검사기 논리 내에서 확인란 값을 참조 할 수 있습니다.

도움이 되었기를 바랍니다!

편집 : 업데이트 된 링크 및 예제. 답변을 작성하는 동안 코드가 변경되었습니다.

EDIT_2 : alpha.48은 EventEmitter.observer를 EventEmitter.subscribe로 변경합니다!

EDIT_3 : 실제 구현에 대한 링크 변경, 문서에 대한 링크 추가

Validaton- 가이드

FormControl 문서


내 ControlGroup을 사용하면 터치 여부를 확인하는 오류 div가 있기 때문에이 작업을 수행합니다.

for (var i in this.form.controls) {
  this.form.controls[i].markAsTouched();
}

(this.form은 내 ControlGroup입니다)


이 블로그의 도움으로

블로그 링크

나는 Nightking 대답의 결합으로 해결책을 찾았습니다.

Object.keys(this.orderForm.controls).forEach(field => {
       const control = this.orderForm.get(field);
       control.updateValueAndValidity();

});

this.orderForm 은 양식 그룹입니다.


There are more elegant ways of modeling this behavior - for example, putting your state into a ReplaySubject and observing that, and then using async validators observing the state - but the pseudo-coded approach below should work. You simply observe the value changes in the checkbox, update the model as appropriate, then force a re-validation of the numberFld with the updateValueAndValidity cal.

constructor(builder: FormBuilder) {
  this.formData = { num: '', checkbox: false };
  const numberFld = builder.control(this.formData.num, myValidators.numericRange);

  const checkbox = builder.control(this.formData.checkbox);
  checkbox.valueChanges.map(mapToBoolean).subscribe((bool) => {
    this.formData.checked = bool;
    numberFld.updateValueAndValidity(); //triggers numberFld validation
  });

  this.formGp = builder.group({
      numberFld: numberFld,
      checkboxFld: checkbox
  });
}

static minMaxRange(min: number, max: number): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
        if (Validators.min(min)(control)) { // if min not valid
            return Validators.min(min)(control);
        } else {
            return Validators.max(max)(control);
        }
    };
}

This did the trick for me

this.myForm.markAllAsTouched();

참고URL : https://stackoverflow.com/questions/32260082/does-anybody-know-how-to-trigger-form-validators-in-angular2

반응형