angular material stepper add new step items dynamically on every click

后端 未结 2 1625
失恋的感觉
失恋的感觉 2021-01-05 01:12

I am using angular material in my project. I want to add extra stepper item(mat-step) on every click of addItem button.

I created a plunker here. https:

相关标签:
2条回答
  • 2021-01-05 01:20

    I would use FormArray along with FormGroup

    HTML:

    <button mat-raised-button (click)="addItem()">
      add item
    </button>
     <form [formGroup]="formGroup">
      <mat-horizontal-stepper  formArrayName="form">
        <mat-step [formGroupName]="i" *ngFor="let customerGroup of formGroup.controls.form.controls; let i = index">
          <ng-template matStepLabel>Step {{i + 1}}</ng-template>
          <mat-form-field>
            <input matInput placeholder="Address" formControlName="cont" required>
          </mat-form-field>
        <div>
          <button mat-button matStepperPrevious>Back</button>
          <button mat-button matStepperNext>Next</button>
        </div>
        </mat-step>
      </mat-horizontal-stepper>
    </form>
    

    TS Code:

    import {Component, OnInit} from '@angular/core';
    import {FormBuilder, FormControl,FormGroup, Validators,FormArray} from '@angular/forms';
    
    /**
     * @title Stepper overview
     */
    @Component({
      selector: 'stepper-overview-example',
      templateUrl: 'stepper-overview-example.html',
      styleUrls: ['stepper-overview-example.css'],
    })
    export class StepperOverviewExample implements OnInit {
      isLinear = false;
      formGroup : FormGroup;
      form: FormArray;
      constructor(private _formBuilder: FormBuilder) {    
      }
    
      ngOnInit() {
        this.formGroup = this._formBuilder.group({
          form : this._formBuilder.array([this.init()])
        }) 
        this.addItem();
      }
    
      init(){
        return this._formBuilder.group({
          cont :new FormControl('', [Validators.required]),
        })
      }
    
      addItem(){
        this.form = this.formGroup.get('form') as FormArray;
        this.form.push(this.init());
      }
    }
    

    Stackblitz

    0 讨论(0)
  • 2021-01-05 01:24

    You can use FormGroup and FormArray to archive this.

    Check the below example for that

    https://stackblitz.com/edit/dynamic-stepper-material

    0 讨论(0)
提交回复
热议问题