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.
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With