Vlad Topala
Vlad Topala

Reputation: 916

What is the cleanest way to pass a formGroup to a mat-step?

I'm trying to use the stepper component from angular-material together with reactive forms. The problem is that I don't what is the best way (from an architectural point of view) to allow each mat-step to access a formGroup.

Looking at the two examples below, it seems that the easiest way is to create formGroup1 and formGroup2 outside of the stepper (example 1). My issue with this approach is that inside each <form> I want to have only one custom component that contains its one formGroup and I don't think the container of the stepper should know about the formGroups. Is there any way to achieve this?

<parent that declares formGroup1>
    <mat-vertical-stepper linear>
      <mat-step [stepControl]="formGroup1">
        <form [formGroup]="formGroup1">
            <component that uses formGroup1></component>
        </form>
      </mat-step>
    <<mat-vertical-stepper>
</parent>

<parent oblivious to formGroup2>
    <mat-vertical-stepper linear>
        <mat-step [stepControl]="formGroup2">
            <form [formGroup]="formGroup2">
                <component declaring formGroup2></component>
            </form>
         </mat-step>
    </mat-vertical-stepper>
</parent>

Solutions that I have considered:

I'd like to know if there's one good solution for this. It feels like I'm missing something very obvious.

Upvotes: 1

Views: 1856

Answers (1)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

I had the same issue in our application and I went with the @Output() approach. Don't know if it is the best, but it was working fine.

Parent Component html

<mat-step
        [stepControl]="form1"
        label="Step1"
        [completed]="form1?.valid">
      <app-step-one [(form)]="form1"></app-step-one>
    </mat-step>

Parent Component

form1: FormGroup;

Child Component html

<form [formGroup]="form">
.....
</form>

Child Component ~ You could inherit that for every step from a parent class

  _form: FormGroup;

  @Input()
  get form() {
    return this._form;
  }

  @Output()
  formChange = new EventEmitter();
  set form(value) {
    this._form = value;
    this.formChange.emit(this._form);
  }

  ngOnInit() {
    this.form = this.fb.group({
      item: new FormControl('', Validators.required),
    });
  }

Upvotes: 3

Related Questions