programing tip

언제 FormGroup과 FormArray를 사용합니까?

itbloger 2020. 11. 15. 10:58
반응형

언제 FormGroup과 FormArray를 사용합니까?


FormGroup :

FormGroup는 키 각 컨트롤의 이름으로, 하나의 객체로 각 자식 FormControl의 값을 집계합니다.

const form = new FormGroup({
  first: new FormControl('Nancy', Validators.minLength(2)),
  last: new FormControl('Drew'),
});

FormArray :

FormArray는 배열로 각 하위 FormControl의 값을 집계.

const arr = new FormArray([
  new FormControl('Nancy', Validators.minLength(2)),
  new FormControl('Drew'),
]);

하나는 언제 다른 것보다 사용해야합니까?


FormArray는 FormGroup의 변형입니다. 주요 차이점은 데이터가 배열로 직렬화된다는 것입니다 (FormGroup의 경우 객체로 직렬화되는 것과 반대). 이는 동적 양식과 같이 그룹 내에 얼마나 많은 컨트롤이 있을지 모르는 경우에 특히 유용 할 수 있습니다.

간단한 예를 들어 설명하겠습니다. 피자에 대한 고객의 주문을 캡처하는 양식이 있습니다. 그리고 특별 요청을 추가하고 제거 할 수있는 버튼을 배치합니다. 다음은 구성 요소의 html 부분입니다.

<section>
  <p>Any special requests?</p>
  <ul formArrayName="specialRequests">
    <li *ngFor="let item of orderForm.controls.specialRequests.controls; let i = index">
      <input type="text" formControlName="{{i}}">
      <button type="button" title="Remove Request" (click)="onRemoveSpecialRequest(i)">Remove</button>
    </li>
  </ul>
  <button type="button" (click)="onAddSpecialRequest()">
    Add a Request
  </button>
</section>

다음은 특수 요청을 정의하고 처리하는 구성 요소 클래스입니다.

constructor () {
  this.orderForm = new FormGroup({
    firstName: new FormControl('Nancy', Validators.minLength(2)),
    lastName: new FormControl('Drew'),
    specialRequests: new FormArray([
      new FormControl(null)
    ])
  });
}

onSubmitForm () {
  console.log(this.orderForm.value);
}

onAddSpecialRequest () {
  this.orderForm.controls
  .specialRequests.push(new FormControl(null));
}

onRemoveSpecialRequest (index) {
  this.orderForm.controls['specialRequests'].removeAt(index);
}

FormArray는 FormGroup의 "addControl", "removeControl", "setValue"등을 사용하는 것보다 "push", "insert"및 "removeAt"을 사용하여 FormControls를 조작하는 것이 더 쉽다는 점에서 FormGroup보다 더 많은 유연성을 제공합니다. FormArray 메서드는 컨트롤이 양식의 계층 구조에서 제대로 추적됩니다.

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


반응 형을 만들려면 부모 FormGroup가 필수입니다. 여기 FormGroup에는 formControls, child formGroups또는formArray

FormArray can further contain array of formControls or a formGroup itself.

When should we use formArray?

Please read this beautiful post which explains the usage of formArray

The interesting example in that blog is about the trips formGroup

The structure of trips formGroup using formControl and formArray would look something like:

this.tripForm = this.fb.group({
    name: [name, Validators.required],
     cities: new FormArray(
       [0] ---> new FormGroup({
           name: new FormControl('', Validators.required),
               places: new FormArray(
                  [0]--> new FormGroup({
                      name: new FormControl('', Validators.required),
                         }),
                      [1]--> new FormGroup({
                         name: new FormControl('', Validators.required),
                      })
                  )
              }), 
       [1] ---> new FormGroup({
           name: new FormControl('', Validators.required),
           places: new FormArray(
               [0]--> new FormGroup({
                   name: new FormControl('', Validators.required),
               }),
               [1]--> new FormGroup({
                   name: new FormControl('', Validators.required),
               })
               )
      }))
})

Do not forget to play with this DEMO, and notice the usage of array for cities and places of a trip.


From angular documentation you can see that

FormArray is an alternative to FormGroup for managing any number of unnamed controls. As with form group instances, you can dynamically insert and remove controls from form array instances, and the form array instance value and validation status is calculated from its child controls. However, you don't need to define a key for each control by name, so this is a great option if you don't know the number of child values in advance.

Let me show you their example and try to explain how I understand this. You can see source here

Imagine a form witch has following fields

  profileForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
    aliases: this.fb.array([
      this.fb.control('')
    ])
  });

Here we have firstName, lastName, address and aliases All field together are form group so we wrap everything in group. At the same time address is like a subgroup so we wrap it in another group (You can look at template for better understanding)! Every form control here hes key except aliases and it means that you can push in it values as much as you want like simple array using formBuilder methods like push.

This is how I understand it, hope it helps someone.

참고URL : https://stackoverflow.com/questions/41288928/when-to-use-formgroup-vs-formarray

반응형