Ahelp
Ahelp

Reputation: 313

Set default values to formArray in Angular 6

Contact Model,

interface Contact {
  name:string;
  age:number;
}

Contact component, contacts array initialized with values ,

export class ContactComponent {

 contacts: Contact[] = [{name:'xyz', age:30}, {name:'abc', age: 25}];
 contactForm: FormGroup;

 constructor(private fb: FormBuilder) {
  this.contactForm = this.fb.group({
   contacts: this.fb.array([this.createContact()])
  });
 }

 createContact(): FormGroup {
    return this.fb.group({
       ???????? - How can initialize values here. 
    });
 }

}

Any other better way of designing it?

Upvotes: 3

Views: 10501

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39482

You can map through the contacts and transform each element in contacts into a FormGroup and set it as a part of your contacts FormArray.

For transforming a contact into a Contact FormGroup you can simply pass the contact object as an arg to a function which will use these values and set them as the default values of the controls.

Try this:

    contacts: Contact[] = [{
      name: 'xyz',
      age: 30
    }, {
      name: 'abc',
      age: 25
    }];
    contactForm: FormGroup;
    
    constructor(private fb: FormBuilder) {}
    
    ngOnInit() {
      this.contactForm = this.fb.group({
        contacts: this.fb.array(this.contacts.map(contact => this.createContact(contact)))
      });
    
      console.log(this.contactForm.value);
    
    }
    
    createContact(contact): FormGroup {
      return this.fb.group({
        name: [contact.name],
        age: [contact.age]
      });
    }

Here's a Sample StackBlitz for your ref.

Upvotes: 8

Related Questions