2

i have an angular4 form which is built using form builder. The code is as follows.

initializeFromControls() {
    let obj = {
      firstname: new FormControl('', ),
      lastname: new FormControl('', ),
      email: new FormControl('',
              [Validators.required,
              Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$")]),
      status: new FormControl('', ),
      role_id: new FormControl(''),
      account_ids: this.formBuilder.array([])         
    }
    this.userFrm = this.formBuilder.group(obj);
  }

Now i have another field named account_ids which is an array. The account ids are fetched from the getAccounts api call.

ngOnInit() {
    this.initializeFromControls();
    this.getAccounts();
  }

Selected Account ids are send to backend using the following code.

onChange(account_id:string, isChecked: boolean) {
    const accountIdArray = <FormArray>this.userFrm.controls.account_ids;

    if(isChecked) {
      accountIdArray.push(new FormControl(account_id));
    } else {
      let index = accountIdArray.controls.findIndex(x => x.value == account_id)
      accountIdArray.removeAt(index);
    }

    console.log(this.userFrm.getRawValue());
  }

Now I need to pre-populate account ids (formArray) on edit page.

The template is as follows.

<div *ngFor="let account of accounts">
              <input type="checkbox" (change)="onChange(account.id, $event.target.checked)">{{account.id}}  {{account.acc_name}}<br>
            </div>

Any idea on how to achieve this?

1

1 Answer 1

2

Your initialization is fine. Here how I did in my case where on the edit page I had to prepopulate FormArray:

items: FormArray;

//response from server
response['data'].map((item, index) => {

    const tmpDict = {};
    tmpDict['firstname'] = new FormControl(item.firstname);
    tmpDict['lastname'] = new FormControl(item.lastname);
    tmpDict['email'] = new FormControl(item.email);

   this.items = this.userFrm.get('items') as FormArray;
   this.items.push(new FormGroup(tmpDict));
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.