8

Hi i am working with Angular material and i have an Array of products that creates a table in my template

 <tbody>
    <tr *ngFor="let item of productArray | async; let i = index">

Inside this loop i have another loop on a <th> tag:

<th>
   <mat-form-field>
      <mat-select placeholder="Length" formControlName="lengthOption" [compareWith]="compareWith" [(value)]="item.lengthOption">
         <mat-option *ngFor="let lengthOption of item.lengthOptions" [value]="lengthOption">
              {{lengthOption.name}}
         </mat-option>
      </mat-select>
   </mat-form-field>

I would like to make use of the two way binding of [(value)].

I know i can set [value] to be lengthOption.name for example and then set the binding to [(Value)]="selected" and then i can set this in my component (selected = whatever) or view it in the template via {{selected}}.

My query is can i get this value from the parent array like i am trying in the inner loop:

*ngFor="let item of productArray | async; let i = index"

[(value)]="item.lengthOption"

lengthOption does exist on productArray.

The point of this i want to set a initial selected value for each products mat-select.

lengthOption looks like { "id": 1, "name": "Ten Years" }

So i am trying to set the object to the mat-option from a parent array, not just a object value form its own array.

Thanks in advance.

David
  • 641
  • 1
  • 8
  • 23

2 Answers2

1

you can add a new property to item (the selected one) and change it on ngModelChange

 <mat-select placeholder="Length" formControlName="lengthOption" (ngModelChange)="select($event, item)" [compareWith]="compareWith" [(value)]="item.lengthOption">
     <mat-option *ngFor="let lengthOption of item.lengthOptions" [value]="lengthOption">
        ...

and try something like this to change each time you select a new one :

select(selectedValue, item) {
 item['selectedLengthOption'] = selectedValue;
}

and you can access it in your template inside your loop

{{item.selectedLengthOption}}
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
-2

Two way binding is not suggested with dynamic name and it doesn't work in expected way. Treat this [(value)] as [(ngModel)]

You may use (onChange) or if you want to do need to get all form status/info and if your product array has more item, try using formArray it will make your life easy. https://angular.io/api/forms/FormArray

Rashmi Kumari
  • 520
  • 4
  • 15