Home > Mobile >  Set formControlName to Template Variable
Set formControlName to Template Variable

Time:02-14

I'm working in an Angular v12 project. I have a form with many controls. In my template, I'm creating loops to display these controls. The controls are displayed in blocks in various positions (so all the outer divs matter).

When I set up these loops with a span, it works fines and shows the value of control I need:

<div  *ngFor="let rowGroup of rowGroups">
   <div  *ngFor="let group of rowGroup">
      <div  *ngFor="let i of [1,2,3]">
         <div  *ngFor="let j of [1,2,3]">
            <span>
              {{this.form.get(group '-' i '-' j)?.value}}
            </span>
         </div>
      </div>
   </div>
</div>

But now, instead of a span, I want to be able to use a material input. But I need to be able to set the formControlName to the template variables (group '-' i '-' j).

<div  *ngFor="let rowGroup of rowGroups">
   <div  *ngFor="let group of rowGroup">
      <div  *ngFor="let i of [1,2,3]">
         <div  *ngFor="let j of [1,2,3]">
            <mat-form-field appearance="outline">
               <input matInput formControlName="{{VARIABLE(group '-' i '-' j) HERE?}}">
            </mat-form-field>
         </div>
      </div>
   </div>
</div>

Is there a way to do that?

CodePudding user response:

You simply need to bind it as:

formControlName="{{group '-' i '-' j}}"

So your html would be something as below:

<form [formGroup]="form"> <!-- You would need this binding too  -->
  <div  *ngFor="let rowGroup of rowGroups">
    <div  *ngFor="let group of rowGroup">
      <div  *ngFor="let i of [1,2,3]">
        <div  *ngFor="let j of [1,2,3]">
          <mat-form-field appearance="outline">
            <input matInput formControlName="{{group '-' i '-' j}}">
          </mat-form-field>
        </div>
      </div>
    </div>
  </div>
</form>

PS: The above should work if {{this.form.get(group '-' i '-' j)?.value}} worked for you. In case if it doesn't work, please do share the form FormGroup structure defined in ts file.

  • Related