Skip to content

How to push object to forms in angular?

How to push the roles form data value to createUserForm data value so that they will become 1 object ?

#The final result should look like this

{
    "emailAddress": "asdasdas@gmail.com",
    "firstName": "sdsfd",
    "lastName": "fsdfsdf",
    "phoneNumber": "21324",
    "companyName": "sdfsdf",
    "title": "CEO",
    "roleId": 7,
    "associatedAccount": "WALLS",
    "accountId": 4,
    "roles": [
        {
            "id": 12,
            "name": "Architect",
            "isShow": true,
            "transactionRoleId": 12
        },
        {
            "id": 11,
            "name": "Construction Project Director",
            "isShow": true,
            "transactionRoleId": 11
        },
        {
            "id": 9,
            "name": "COVP",
            "isShow": true,
            "transactionRoleId": 9
        }
    ]
}

This is the data from roles when I submit

 {
        "id": 12,
        "name": "Architect",
        "isShow": true,
        "transactionRoleId": 12
    }

This is the data from createUserForm when I submit

{
    "emailAddress": "adasd",
    "firstName": "asdasdasd",
    "lastName": "asdasd",
    "phoneNumber": "2132",
    "companyName": "adasdas",
    "title": "dasdasdas",
    "roleId": 7,
    "associatedAccount": "test",
    "accountId": 4
}

—>>> another form

roles = new FormControl();

—>>>> User Form

 createUserForm = new FormGroup({
    emailAddress: new FormControl(),
    firstName: new FormControl(),
    lastName: new FormControl(),
    phoneNumber:  new FormControl(),
    companyName: new FormControl(),
    title: new FormControl(),
    roleId: new FormControl(),
    associatedAccount: new FormControl(),
    accountId: new FormControl(),
  });

—>>> what i tried

 saveUser() {
        this.createUserForm.get('roleId').setValue(7);
        console.log("this.createUserForm.value" , this.createUserForm.value)
        console.log("data" ,this.roles.value)
        console.log("finaldata : " ,
 this.createUserForm.value.push(this.roles.value))

Answer

You can achieve this by using angular reactive form try this out.

 import { FormArray, FormBuilder, FormGroup } from '@angular/forms';

 form: FormGroup;

 constructor(private _fb: FormBuilder) {}

 this.form = this._fb.group({
  firstName: [],
  emailAddress: [],
  ...
  roles: this._fb.array([]) // create a role form field as an array
});

You can call a method to add role object to form array

addRole(): void {
  const roles = this.form.get('roles') as FormArray;

  roles.push(
     this._fb.group({ id: [], name: [], isShow: [], transactionRoleId: [] 
    })
  );

  console.log(this.form.value);
}

Or can remove the added role by its index

removeRole(index: number): void {
  const roles = this.form.get('roles') as FormArray;

  roles.removeAt(index);
}