Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to implement Form Array in custom multi-step form using Angular-12.

Component:

export class ProfileEditComponent implements OnInit {

  isLinear = true;
  isLoading = false;
  isSubmitted = false;
  multistepForm!: FormGroup;
  step: any = 1;

  constructor(
    private fb: FormBuilder
  ) {}

  ngOnInit(): void {
    this.buildForm();
  }

  onFormSubmit() {
    this.step = this.step + 1;
  }

  previous() {
    this.step = this.step - 1;
  }

  buildForm() {
    this.multistepForm = this.fb.group({
      //  multistepDetails: new FormGroup({
      personalDetails: new FormGroup({
        first_name: new FormControl('', [Validators.required, Validators.maxLength(50)]),
        last_name: new FormControl('', [Validators.required, Validators.maxLength(50)]),
        other_name: new FormControl('', [Validators.maxLength(50)]),
      }),
      educations: this.fb.array([
        this.createEducation()

      ])
    });
  }

  createEducation() {
    return this.fb.group({
      educationDetails: new FormGroup({
        city: new FormControl('', Validators.minLength(3)),
        country: new FormControl('', Validators.minLength(3))
      }),
    })
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
165 views
Welcome To Ask or Share your Answers For Others

1 Answer

In step 2 you have not given educations formArray reference in HTML. So to get those Formarray or Forgroup[] you need to create one property on your ProfileEditComponent as below:

get educations(): FormGroup[] {
    return (<FormArray>this.multistepForm.controls['educations']).controls as FormGroup[];
}

This will return you all the educations in the form of FormGroup[]. Now you have to use this to bind your controls on HTML. So in your HTML you need to change your step 2 this way:

<div class="card-body" *ngIf="step == 2">
    <div *ngFor="let item of educations; index as i">
      <div [formGroup]="item">
        <div formGroupName="educationDetails">
          <h4>Education Details</h4>
          <hr>
          <div>
            <label for="city">City:</label>
            <input type="text" formControlName="city">
          </div>
          <div>
            <label for="country">Country:</label>
            <input type="text" formControlName="country">
          </div>
        </div>
      </div>
    </div>
  </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...