Home > Blockchain >  How to print formControlName value in html template
How to print formControlName value in html template

Time:10-04

I want to print the value of fontControlName in the HTML template I tried different ways but nothing is working. The below code is working fine and values are printed in input.

Angular version 12

HTML

  <div formArrayName="billings" *ngFor="let bill of billings.controls;  let i = index;">
    <div [formGroupName]="i">
      <div>
        <tr>
          <td>
          {{bill.get('heads')}} print object object
          {{bill.get('heads').value}} <-- possible null compile time error-->
            <input class="form-control" type="text" formControlName="heads">
          </td>
          <td>
            <input class="form-control" type="number" step=".01" formControlName="amount">
          </td>
        </tr>
      </div>
    </div>
  </div>
</form>

Component

constructor(private fb: FormBuilder, private transactionService: TransactionService) {
    this.maintenanceForm = this.fb.group({
      billings: this.fb.array([])
    })
  }

  setExistingMaintenance(billings: IRegularMaintenaceI[]): FormArray {
    const formArray = new FormArray([]);
    billings.forEach(bill => {
      formArray.push(this.fb.group({
        heads: bill.accountHeads.heads,
        amount: bill.amount
      }))
    });

    return formArray;
  }```
[Solution but not working for me][1]: https://stackoverflow.com/questions/47328175/how-do-i-display-a-formarray-of-grouplists

CodePudding user response:

Add method in your ts file to get control

  getControlByName(groupIndex: number, controlName: string): FormControl{
    const fg = this.billings.at(groupIndex) as FormGroup;
    return fg.get(controlName) as FormControl;
  }

And {{ getControlByName(i, 'heads').value }} in the template to get value, use group-index and control-name to retrieve formControl.

<div [formGroupName]="i">
  ..
      
      {{ getControlByName(i, 'heads').value }}
      
        <input class="form-control" type="text" formControlName="heads">
      ..
      

Angular demo

  • Related