0

In angular 7 , I am trying to make editable form with some initial values. I created a formgroup which also has formarray. I am trying to dynamically assign values to formcontrols , within formarray but formcontrol values are not being displayed on form.

Here is my html,

<form [formGroup]="UserForm" (ngSubmit)="submit()" >
  <ng-container>
    <span>Group Name</span>
    <mat-form-field id="uName">
      <input matInput autocomplete="off" formControlName="GroupName">
    </mat-form-field>
  </ng-container>
  <br>
  <span>User Details</span>
  <br> 
  <div id="divUser"> 
      <table mat-table [dataSource]="UserData" class="mat-elevation-z8" formArrayName="UserRow">
          <ng-container matColumnDef="id">
              <th mat-header-cell *matHeaderCellDef> Id </th>
              <td mat-cell *matCellDef="let row; let index = index" [formGroupName]="index">
                  {{index + 1}}.
              </td>         
          </ng-container>

          <ng-container matColumnDef="username">
              <th mat-header-cell *matHeaderCellDef>Server Name</th>
              <td mat-cell *matCellDef="let row; let index = index" [formGroupName]="index">
                  <mat-form-field>
                    <input matInput formControlName="username" autocomplete="off">  // this is showing blank fields
                  </mat-form-field>  
              </td>         
          </ng-container>

          <tr mat-header-row *matHeaderRowDef="UserColumns"></tr>
          <tr mat-row *matRowDef="let row; columns: UserColumns;"></tr>
      </table>   
  </div> 
  <button mat-raised-button type="submit" color="primary">Submit</button>
</form>

And component code,

export class AdmissionComponent implements OnInit {
  public UserForm: FormGroup;
  public UserData;
  public UserColumns = ['id','username']  

  constructor(private formservice: AdmissionService,private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.getservicedata('FIRST')
    this.UserForm = this.formBuilder.group({
      GroupName: new FormControl(),     
      UserRow: this.formBuilder.array([this.CreateUser()])      
    });
  }

  onsetValue(result): void { 
    this.UserForm.controls['GroupName'].setValue(result.data[0].GroupName) // This is working and showing on html.      

    for (var key in result.data[0].usersRow) {
      if (key != '0'){ this.fnUserAdd(); }      
      // this.UserForm.value.UserRow[key].username = result.data[0].usersRow.username; // this is not working.
      this.UserForm.value.UserRow[key].username = 'testing'; // this is not wroking either
        };

        console.log(this.UserForm.value) // BUT this is perfactly showing data after setting up the values.
    }

    fnUserAdd(){
        (this.UserForm.get('UserRow') as FormArray).push(this.CreateUser());
        return this.getUserData();
    }
    getUserData(){
      this.UserData = this.UserForm.get('UserRow').value;
    }
    CreateUser(): FormGroup {
        return this.formBuilder.group({
          username: '',
          userrole: '',      
          present:''
        })
    }
    getservicedata(UserId){    
        return this.admiserv.getDetails(UserId)
        .subscribe(
          result => {
            this.onsetValue(result)         
          });
    }
  submit(){
    console.log(this.UserForm.value)
  }
}

It shows blank input fields on html and when i put some values and click submit, it works and sends the values to function but not showing initial values in input fields.

Please suggest how to resolve this error.

Thanks

5
  • 1
    Can you please create a sample on stackblitz for this. Commented Jul 15, 2019 at 6:12
  • You have a duplicate identifier named formservice in your implementation. Plus you're also injecting two services as dependencies. Please share a minimal implementation of those two services as well. Commented Jul 15, 2019 at 6:18
  • Thanks @SiddAjmera. I changed the function name and updated question as well but still no difference. Commented Jul 15, 2019 at 6:27
  • I didn't say it will fix the issue at hand. I just said that we need more information in order to fix the issue at hand. Would you mind creating a sample stackblitz to work with and share it across so that we could have a look into it? Commented Jul 15, 2019 at 6:31
  • @SiddAjmera , i have been trying to create it on stackblitz since morning but not able to fr various errors. Commented Jul 15, 2019 at 9:03

1 Answer 1

3

Always use setValue -or pathValue- to give value to a FormControl, FormArray or FormGroup-. So, I supouse you want write something like

const array=this.UserForm.get('UserRow') as FormArray;
for (var row of result.data[0].usersRow) {
   array.push(this.CreateUser());
   array.at(array.length-1).setValue(row)
  //or array.at(array.length-1).setPathValue({username:'test'})
}

Really, I suggest you change your function CreateUser by some like

CreateUser(data:any): FormGroup {
   data={username:'',userrole:'',present:'',...data}
   return this.formBuilder.group({
          username: data.username,
          userrole: data.userrole,      
          present:data.present
   })
}

So you can simple

const array=this.UserForm.get('UserRow') as FormArray;
for (var row of result.data[0].usersRow) {
   array.push(this.CreateUser(row));
  //or array.push(this.createUser({username:'test'})
}

and if you want create an empty formGroup, call as

this.CreateUser(null)

See stackblitz

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Eliseo but It is not working. throwing error "Cannot read property 'username' of null" in suggested function CreateUser(data:any). And how the ngInit line "UserRow: this.formBuilder.array([this.CreateUser()]) " will change ?
::glups:: a sintax mistake (are username:data.username,... -before username:data:''... I forgot remove the :'' from a before coded-. Just corrected in answer. added a stackblitz. My apologies :(
Yes @Eliseo, i corrected this and it worked. Thanks a lot. I also learnt spread syntax from your answer. :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.