3

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?

1 Answer 1

8

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.

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.