我想使用ngFor动态添加显示值(在<mat-option>
中)。在我的HTML代码中,我在<mat-option>
下添加了{{'selected'+ displayValue}},并且在类中定义了“ displayValue”。有人可以帮忙吗?
谢谢。
<mat-form-field>
<mat-select placeholder="Favorite food"
[(ngModel)]="selectedValueModel"
(ngModelChange)="changedValue($event)" name="food" [compareWith]="compFn">
<mat-option *ngFor="let selected of SelectedObjectData" [value]="selected">
{{'selected'+ displayValue}}
</mat-option>
</mat-select>
</mat-form-field>
export class SelectboxComponent {
displayValue= 'viewValue'
SelectedObjectData: any[] = [{ value: 'steak-0', viewValue: 'Steak' },
{ value: 'pizza-1', viewValue: 'Pizza' },
{ value: 'tacos-2', viewValue: 'Tacos' }];
@Input() selectedValueModel = {value: 'tacos-2', viewValue: 'Tacos'};
@Output() selectedValueModelChange = new EventEmitter()
changedValue(newValue: any) {
this.selectedValueModel = newValue
this.selectedValueModelChange.emit(newValue)
}
compFn(c1: any, c2: any): boolean {
return c1 && c2 ? c1.value === c2.value : c1 === c2;
}
}
答案 0 :(得分:1)
您可以在html mat-option中使用它
{{selected[displayValue]}}
答案 1 :(得分:0)
我认为您的绑定错误。您的displayValue
将始终在视图上显示字符串'viewvalue'。为了显示所选食物和其他选项的显示,您需要使用对绑定的selected
对象的访问,并选择要在视图上显示的viewValue
字符串属性。
我在下面做了相关的编辑。
component.html:
<mat-form-field>
<mat-select placeholder="Favorite food"
[(ngModel)]="selectedValueModel"
(ngModelChange)="changedValue($event)" name="food" [compareWith]="compFn">
<mat-option *ngFor="let selected of SelectedObjectData" [value]="selected">
{{'selected'+ selected.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
component.ts:
export class SelectboxComponent {
displayValue= 'viewValue'
SelectedObjectData: any[] = [{ value: 'steak-0', viewValue: 'Steak' },
{ value: 'pizza-1', viewValue: 'Pizza' },
{ value: 'tacos-2', viewValue: 'Tacos' }];
@Input() selectedValueModel = {value: 'tacos-2', viewValue: 'Tacos'};
@Output() selectedValueModelChange = new EventEmitter()
changedValue(newValue: any) {
//this.selectedValueModel = newValue
//this.selectedValueModelChange.emit(newValue)
// selected value will be reflected here, do what you want with the newValue object
console.log(newValue)
}
compFn(c1: any, c2: any): boolean {
return c1 && c2 ? c1.value === c2.value : c1 === c2;
}
}