0

I have a formArray that's a list where you can add, edit and delete. Everything works fine but I would like to set the initial value for the first two itmes. It works fine for the input value but my mat-autocomplete is not populating correctly. here is the stackblitz.

.TS FILE

  initItems() {
    var formArray = this.fb.array([]);

    for (let i = 0; i < 2; i++) {
      formArray.push(
        this.fb.group({
          unititem: ['syed', [Validators.required]],
          age: ['14', [Validators.required]]
        })
      );
    }
    return formArray;
  }
 
Flash
  • 924
  • 3
  • 22
  • 44

1 Answers1

1

You need to init unititem with the object option like :

for (let i = 0; i < 2; i++) {
  formArray.push(
    this.fb.group({
      unititem: [this.options[0], [Validators.required]],
      age: ['14', [Validators.required]]
    })
  );
}

Update based on comment:

You can find the name into your array of obect like

for (let i = 0; i < 2; i++) {
  formArray.push(
    this.fb.group({
      this.options.find(({ itemName }) => itemName === 'syed'),
      age: ['14', [Validators.required]]
    })
  );
}
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • That works for this example but what it its saved data you are trying to populate. how would you know which option to use if you only know the name – Flash Jul 15 '21 at 13:21
  • Thanks is that the only way though. I found this example online but my real issue is the dropdown is coming from a service that filters as you type. – Flash Jul 15 '21 at 13:39