Programing

Angular 2 : 반응 형 컨트롤을 반복합니다.

lottogame 2020. 11. 3. 07:35
반응형

Angular 2 : 반응 형 컨트롤을 반복합니다.


markAsDirty내부의 모든 컨트롤 을 원합니다 FormGroup.


Object.keys이걸 처리 할 수 있다는 걸 알아 냈 어요

Object.keys(this.form.controls).forEach(key => {
  this.form.get(key).markAsDirty();
});

Angular 8+의 경우 다음을 사용하십시오 (Michelangelo 답변 기준).

Object.keys(this.form.controls).forEach(key => {
  this.form.controls[key].markAsDirty();
});

그만한 가치를 위해, Object.keys (...) 매직 을 사용하지 않고도이 작업을 수행 할 수있는 또 다른 방법이 있습니다 .

for (const field in this.form.controls) { // 'field' is a string

   const control = this.form.get(field); // 'control' is a FormControl

}

허용되는 대답은 플랫 양식 구조에 맞지만 원래 질문에 완전히 대답하지는 않습니다. 웹 페이지에는 중첩 된 FormGroups 및 FormArrays가 필요할 수 있으며 강력한 솔루션을 만들려면이를 고려해야합니다.

public markControlsDirty(group: FormGroup | FormArray): void {
    Object.keys(group.controls).forEach((key: string) => {
        const abstractControl = group.controls[key];

        if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
            this.markControlsDirty(abstractControl);
        } else {
            abstractControl.markAsDirty();
        }
    });
}

    Object.keys( this.registerForm.controls).forEach(key => {
       this.registerForm.controls[key].markAsDirty();
    });


@Marcos 답변을 사용하여 formGroup을 매개 변수로 전달하는 함수를 만들었으며 모든 formGroup 자식 컨트롤을 더티로 표시하여 서비스 내부에 넣는 코드 주변의 더 많은 곳에서 사용할 수 있도록합니다.

public touchAllFormFields(formGroup: FormGroup): void {
    Object.keys(formGroup.controls).forEach((key) => {
        formGroup.get(key).markAsDirty();
    });
}

도움이 되길 바랍니다;)


getAngular 8에서 양식의 특정 값을 검색하는 데 더 이상 함수가 작동하지 않는 것 같습니다. 그래서 이것이 제가 해결 한 방법이며 답변이 조금 오래 되었기 때문에 더 많은 사용자에게 도움이 될 수 있다고 생각합니다. @Liviu Ilea의 답변을 바탕으로

for (const field in this.myForm.controls) { // 'field' is a string
  console.log(this.myForm.controls[field].value);
}

나는 이것을 만들기 위해이 함수를 생성한다 * 나는 'order'라는 이름의 컨트롤을 가지고 있고 그에게 인덱스를 전달한다.

{"conditionGroups": [
   {
     "order": null,
     "conditions": []
   }
  ]
}


updateFormData() {
    const control = <FormArray>this.form.controls['conditionGroups'];  
    control.value.map((x,index)=>{
    x.order = index; 
 })

이것이 나를 위해 일하는 것입니다.

  private markFormGroupTouched(formGroup: FormGroup) {
      Object.keys(formGroup.controls).forEach((key) => {
      const control = formGroup.controls[key];
      control.markAsDirty();
      if ((control instanceof FormGroup)) {
        this.markFormGroupTouched(control);
      }
 });

}

참고 URL : https://stackoverflow.com/questions/42235156/angular-2-iterate-over-reactive-form-controls

반응형