Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display value of FormControl to label?

Tags:

angular

I have FormGroup that contains FormArray. Each FormControls in FormArray generated by system so it looks like this:

   staffs: FormArray =  { staffs: [
    {id: 1, staffName: "Jimmy", staffRate: 10},
    {id: 2, staffName: "Steffan", staffRate: 20},
    {id: 3, staffName: "Devon", staffRate: 30},
    {id: 4, staffName: "Jonah", staffRate: 50}
    ]}

Now, I want to display all the staff in the component html but I have no idea how to display the staffName inside the label.

The html code as follow

get staffsFA(): FormArray {
  return this.form.get('staffs') as FormArray ;
}
<form [fromGroup]="form">
....
<ng-container formArrayName="staffs">
  <ng-container *ngFor="let sdr of staffsFA.controls; let i=index;">
    <div class="row" [formGroupName]="i">
      <label>[I want staff name in here]</label>
      <input type='text' formControlName="staffRate">
    </div>
  </ng-container>
</ng-container>
....
< /form>

Note: I use Angular 7.

like image 635
nightingale2k1 Avatar asked Dec 23 '22 00:12

nightingale2k1


1 Answers

On your component.ts,

You can access the values of the Form Controls defined within your Reactive Form using by doing something like this:

console.log(this.staffs.value)

For the case of accessing the values of each element within the FormArray, you can do this:

console.log(this.staffs['controls']['staffs']['controls'].value)

Or

console.log(this.staffsFA.value)

Likewise, on your component.html, you can access the individual Form Control values using template interpolation:

   <ng-container *ngFor="let sdr of staffsFA.controls; let i=index;">
    <div class="row" [formGroupName]="i">
      <label>{{ sdr.value.staffName }}</label>
      <input type='text' formControlName="staffRate">
    </div>
  </ng-container>
like image 90
wentjun Avatar answered Dec 28 '22 11:12

wentjun