Reputation: 6867
In my Angular 7 app I'am using the component mat-select of angular material in a reactive form.
The view looks like this :
<mat-form-field class="col-md-3" color="warn">
<mat-select placeholder="Selectionner la boutique"
id="libelleShop"
[(value)]="selectedlibelleShopoValue"
ngDefaultControl
formControlName="libelleShop"
(selectionChange)="onShopSelectionChanged($event)">
<mat-option *ngFor="let shop of shopsList"
[value]="shop">
{{shop.storeName}}
</mat-option>
</mat-select>
Md data is the following :
shopsList= [
{
'edoId': '2119',
'storeName': 'AIX LES BAINS'
},
{
'edoId': '2123',
'storeName': 'ANNEMASSE'
},
{
'edoId': '2460',
'storeName': 'ALENCON'
},
{
'edoId': '2478',
'storeName': 'Grand Evreux Carrefour'
},
{
'edoId': '2632',
'storeName': 'DESTRELAND'
}
]
After the first loading , the options apperead in the select dropdown successfully, and I have a button used to force the value of the mat-select when clicked.
I have tried this:
onClick(){
let shopObjToDisplay = {};
shopObjToDisplay['edoId'] = '2460';
shopObjToDisplay['storeName'] = 'ALENCON';
this.myForm.patchValue({'libelleShop': shopObjToDisplay });
}
Unfortenately it seems that my data is not set.
Any ideas??
Upvotes: 4
Views: 12625
Reputation: 2902
An old question... you can achieve this with the triggerValue
with mat-select and patch value.
<mat-form-field class="full-width" appearance="fill">
<mat-select #level formControlName="level">
<mat-option value="Native Speaker">Native Speaker</mat-option>
<mat-option value="Highly Proficient">Highly Proficient</mat-option>
<mat-option value="Very Good Command">Very Good Command</mat-option>
</mat-select>
</mat-form-field>
With the above, you can now get the value in the template.
<div *ngIf="level.triggerValue && (level.triggerValue).length; else notSpecifiedDate" class="text-muted"
fxFlex="100">{{level.triggerValue}}</div>
<ng-template #notSpecifiedDate>
<div class="text-muted" fxFlex="100">
{{'Not Specified' | translate}}
</div>
</ng-template>
Upvotes: 0
Reputation: 629
Use This:-
onClick(){
let shopObjToDisplay = {};
shopObjToDisplay['edoId'] = '2460';
shopObjToDisplay['storeName'] = 'ALENCON';
this.myForm.patchValue({
libelleShop: shopObjToDisplay
});
}
Upvotes: -1
Reputation: 15121
You need to use the compareWith function on your mat-select input.
Example:
<select [compareWith]="compareFn" [formControl]="selectedCountriesControl">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
Upvotes: 11