Reputation: 701
Let's say I have an interface item with cost and name.
<mat-option *ngFor="let item of list" [value]="item.name">
This is within a mat-autocomplete, and once the user selects a choice, I would like to display both item.cost and item.name, but [value]="item.name" only allows me to show one. How can I concatenate the two values?
Upvotes: 2
Views: 2620
Reputation: 81
in the
<mat-option *ngFor="let item of list" [value]="item.name">
you can access every property of the object (item).
so this:
<mat-option *ngFor="let item of list" [value]="item.name">{{item.name}}({{item.cost}})</mat-option>
//display-> Name (cost)
I suggest to use some Id in [value] property, or just as it was said, the whole object, not the name of the object, in case you have multiple items with same name.
Additionally, if you want to display not only the selected value in the autocomplete, you can use [displayWith]="displayFn"
but you have to put the object as value. [value]="item"
This is the example from documentation:
<form class="example-form">
<mat-form-field class="example-full-width">
<mat-label>Assignee</mat-label>
<input type="text" matInput [formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
And in the .ts file you have to have the displayFn function:
displayFn(user: User): string {
return user && user.name ? user.name : '';
}
in this example de function displays the name, or if it undefined, an empty string.
You can do custom logic on displayFn function, and make sure you are returning the string that you want to display. (displayFn function gots the value of the )
So in your case, you have to pass the object:
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let item of list" [value]="option">
{{option.name}}
</mat-option>
</mat-autocomplete>
And in your .ts file:
displayFn(item): string {
let displayedString = item.name + ' (' + item.cost+ ')'
return displayedString;
}
And your output will be: MyItemName (myItemCost)
Upvotes: 1
Reputation: 5649
Value can be an object
<mat-option *ngFor="let item of list" [value]="item">{{ item.name }}</mat-option>
Upvotes: 2