Home > Software engineering >  How ngSwitch works with ngFor and Inputs form
How ngSwitch works with ngFor and Inputs form

Time:01-25

Look at example below, this code works well(i found the example on some web-sites and made on my platform)

<div  *ngFor="let item of sellHouseFormsArray" [ngSwitch]="item.tag">
     <ng-template  ngSwitchCase="input">
              <div>input works</div>
      </ng-template>
     <ng-template ngSwitchCase="checkbox" >
           <div>checkbox works</div>
     </ng-template>
</div>

However, when i use my code:

   <mdb-form-control  *ngFor="let item of sellHouseFormsArray" [ngSwitch]="item.tag" >
          <ng-template ngSwitchCase="input">
              <input mdbInput mdbValidate  formControlName="{{item.handler}}" type="{{item.type}}" id="{{item.handler}}login"/>
            <label mdbLabel  for="{{item.handler}}">{{item.name}}</label>
          </ng-template>
           <ng-template ngSwitchCase="checkbox" >
             <input mdbInput mdbValidate  formControlName="{{item.handler}}" type="{{item.type}}" id="{{item.handler}}login"  />
             <label mdbLabel  for="{{item.handler}}">{{item.name}}</label>
           </ng-template>
          <ng-template ngSwitchCase="textarea">
            <textarea  mdbInput mdbValidate  id="{{item.handler}}login" rows="4" ></textarea>
            <label mdbLabel  for="{{item.handler}}">{{item.name}}</label>
          </ng-template>
    </mdb-form-control>

doesn't work!

I don't know what happened, why code doesn't work.

Console gives error: TypeError: Cannot read properties of undefined (reading 'input')

CodePudding user response:

Just an idea. Maybe mdb-form-control requires input as direct child, without ng-template. So maybe try repeat mdb-form-control inside loop and switch like:

<ng-container *ngFor="let item of sellHouseFormsArray" [ngSwitch]="item.tag">
  <mdb-form-control  ngSwitchCase="input">
    <input mdbInput mdbValidate  formControlName="{{item.handler}}" type="{{item.type}}" id="{{item.handler}}login"/>
    <label mdbLabel  for="{{item.handler}}">{{item.name}}</label>
...
  • Related