3

I am trying to patch value an array of ids from Firestore into a mat-select with multiple options. I am looping through the array and creating a new form control for each id and then using the reactive form push method to add to the formArray. Like so:

patchValueForm(portfolio: any) {
 this.formGroup.patchValue(portfolio);

 for (const id of portfolio.property_ids) {
   const control = new FormControl(id);
   if (!this.property_ids.getRawValue().includes(id)) {
     this.property_ids.push(control);
   }
}
console.log(this.formGroup.getRawValue()); }

This does seem to patch the value into the form as shown from the console log:

enter image description here

The problem that I am having is that its then not pre populating the material select shown here:

enter image description here

The HTML that I am using for this part is:

 <mat-form-field appearance="outline">
          <mat-select [formArrayName]="'property_ids'" multiple>
            <mat-option *ngFor="let property of properties; let i = index" 
                        (onSelectionChange)="updatePropertyIdArray(property.property_id)" >
              {{property?.address?.first_line_address}}
            </mat-option>
          </mat-select>
          <mat-error>Please select at least one property</mat-error>
        </mat-form-field>

I have searched everywhere online and tried multiple different methods, but still ca not seem to populate the select. Has anyone experienced this before?

1
  • It can be similar to this question Commented Nov 1, 2019 at 12:12

1 Answer 1

3

I would just use a simple formControl instead of the formArray in the mat select. The formControl holds the selection array and u can use formControlName.

 <mat-form-field appearance="outline">
      <mat-select [formControlName]="'property_ids'" multiple>
        <mat-option *ngFor="let property of properties; let i = index" [value]="property.property_id" 
                    (onSelectionChange)="updatePropertyIdArray(property.property_id)" >
          {{property?.address?.first_line_address}}
        </mat-option>
      </mat-select>
      <mat-error>Please select at least one property</mat-error>
    </mat-form-field>

You also need the value binding in the mat option to make the select work properly.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I think im missing something, could you show how to have a formControl with an array value please?
@Jm3s The formControl can hold any value like objects and arrays. You can create such a formControl like new FormControl([]) or new FormGroup({properties: []})

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.