0
{ 
    id: 123,
    email: "[email protected]",
    password: 108,
    myObj:[
    { id:1, name:"abc", age: 20 },
    { id:2, name:"def", age: 21 },
    { id:3, name:"ghi", age: 22 },
    { id:4, name:"jkl", age: 23 } ] 
}

This is how I'm getting the fields from the server to patch, I'm patching them like this :

this.myForm = this.fb.group({
    id: [],
    email: [],
    password: [],
    myObj: [] 
}); 

And I need each of myObj Array to be a separate form control. I tried to access them from the HTML in different ways, (like formControlName = myObj[0] , formControlName = myObj.name ) but no success..

How can I access myObj fields in the HTML?

2
  • 1
    myObj should be formArray, isn't it? Commented May 24, 2018 at 6:50
  • I tried something like this this.myForm = this.fb.group({ id: [], email: [], password: [], myObj: this.fb.array([]) }); but then how do I access it from HTML? as I said formControlName = myObj[0] and formControlName = myObj.name doesn't work.. Commented May 24, 2018 at 7:11

1 Answer 1

6

it should be something like this:

objects: any[] = [];
myObj:[
    { id:1, name:"abc", age: 20 },
    { id:2, name:"def", age: 21 },
    { id:3, name:"ghi", age: 22 },
    { id:4, name:"jkl", age: 23 } ]

ngOnInit() {
    this.myForm = this.fb.group({
        id: [],
        email: [],
        password: [],
        objects: this.formBuilder.array([]) 
    }); 
this.objects = this.myForm.get('objects') as FormArray;
for(let obj of this.myOj){
    this.objects.push(this.createItem());
    }
}

createItem(): FormGroup {
  return this.formBuilder.group({
    id: '',
    name: '',
    age: ''
  });
}

and in template:

<div formArrayName="objects"
  *ngFor="let item of myForm.get('objects').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="id">
    <input formControlName="name">
    <input formControlName="age">
  </div>
</div>
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.