I have a mat-select dropdown, here I am looping through my frequencyArr object.
In ts
frequencyArr = [
{key : "Once daily", abbriviation : '0-0-1'},
{key : "Twice daily", abbriviation : '1-0-1'},
{key : "Thrice daily", abbriviation : '1-1-1'},
{key : "Four times a day", abbriviation : '1-1-1-1'}
]
In html
<mat-select placeholder="frequency" formControlName="frequency" required>
<mat-option *ngFor="let frequency of frequencyArr" [value]="frequency.abbriviation">
<span>{{frequency.key }} : {{ frequency.abbriviation}}</span>
</mat-option>
</mat-select>
What I am trying to do is when open the dialog it will show object key : object value-
<span>{{frequency.key }} : {{ frequency.abbriviation}}</span>
This is fine, but when I select the option it should show only frequency.key into selected field which is not happening.
I tried googling but did not find anything for this case. Any help is appreciated.
To add elements to Select option, we need to use <mat-option> element and to bind value with <mat-option> , use value property of it. To set and get a value for <mat-select> , use value , ngModel , formControl and formControlName property.
The compareWith just literally compares objects by some given values and the checkboxes get selected, if it returns true . In my code, I decided to go with the ng-Model binding but it works with formControl as well: <mat-form-field> <mat-select multiple[compareWith]="compareFn" name="users. [(ngModel)]="users">
The <mat-optgroup> element can be used to group common options under a subheading. The name of the group can be set using the label property of <mat-optgroup> . Like individual <mat-option> elements, an entire <mat-optgroup> can be disabled or enabled by setting the disabled property on the group.
disableOptionCentering: boolean. Whether to center the active option over the trigger. @Input() disableRipple: boolean. Whether ripples are disabled.
You may achieve that by using a mat-select-trigger and a template reference as bellow:
<mat-select placeholder="frequency" required #select>
<mat-select-trigger>
{{ select.value?.abbriviation }}
</mat-select-trigger>
<mat-option *ngFor="let frequency of frequencyArr" [value]="frequency">{{frequency.key }} : {{ frequency.abbriviation}}</mat-option>
</mat-select>
You can do the following to accomplish this.
Set your value to frequency.key
[value]="frequency.key"
Then use <mat-select-trigger
to display the frequency.value
from your formControl
<mat-select-trigger>
{{frequency.value}}
</mat-select-trigger>
Stackblitz
https://stackblitz.com/edit/angular-wxv1wv?embed=1&file=app/select-custom-trigger-example.html
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