angular FormArray

agnusdei1207·2023년 11월 1일
0
 form = new FormGroup({
    numberOfPeople: new FormControl<number>(1, [Validators.required]),
    memberId: new FormControl<string>(this.member().id, [Validators.required]),
    productId: new FormControl<string>('', [Validators.required]),
    departAt: new FormControl<Date>(new Date(), [Validators.required]),
    arriveAt: new FormControl<Date>(new Date(), [Validators.required]),

    representative: new FormGroup({
      name: new FormControl('', [Validators.required]),
      englishName: new FormControl('', [Validators.required]),
      birthDate: new FormControl(null, [Validators.required]),
      tel: new FormControl('', [Validators.required]),
      email: new FormControl<string>('', [Validators.required]),
    }),

    users: new FormArray([
      new FormGroup({
        name: new FormControl('', [Validators.required]),
        englishName: new FormControl('', [Validators.required]),
        birthDate: new FormControl(null, [Validators.required]),
        tel: new FormControl('', [Validators.required]),
      }),
    ]),
  });
 <ng-container *ngFor="let control of form.controls.users.controls; index as i; ">
  </ng-container>
<table
              formGroupName="representative"
              class="w-full text-left border-t-2 border-gray-800"
              placeholder="홍길동"
            >
<lepi-input-text formControlName="name" placeholder="홍길동" />
</table>


 constructor(
    private readonly httpService: HttpService,
    private readonly route: ActivatedRoute,
    private readonly router: Router,
    private readonly store: Store,
    private readonly toastService: ToastService,
    private readonly modalController: ModalController
  ) {
   // 변경 감지 
   this.form.get('numberOfPeople').valueChanges.subscribe((numberOfPeople) => {
      this.updateFormArraySize(numberOfPeople);
    });
  }




updateFormArraySize(numberOfPeople: number) {
    const usersFormArray = this.form.get('users') as FormArray;
    while (usersFormArray.length !== numberOfPeople) {
      if (usersFormArray.length < numberOfPeople) {
        // FormArray에 추가할 FormGroup 생성
        const newUser = new FormGroup({
          name: new FormControl('', [Validators.required]),
          englishName: new FormControl('', [Validators.required]),
          birthDate: new FormControl(null, [Validators.required]),
          tel: new FormControl('', [Validators.required]),
        });
        usersFormArray.push(newUser);
      } else {
        usersFormArray.removeAt(usersFormArray.length - 1);
      }
    }
  }
    <ng-container *ngFor="let control of form.controls.users.controls; index as i; ">
          <table [formGroup]="control" class="w-full text-left border-t-2 border-gray-800">

0개의 댓글