如何在 Angular 中使用 @Input 将 mat-select 选项的密钥作为参数传递

How to pass the key for the mat-select option as param using @Input in Angular

我想根据使用@Input 从 parent 发送到 child 组件的字符串显示 mat-option 的选项值。

请找到下面的代码块

cdropdown.component.ts

@Componenet({
selector: 'mat-dropdown',
templateUrl: 'mat-dropdown.component.html',
styleUrls: ['mat-dropdown.componenet.css']
})
export class dropDownComponent implements OnInit {
 constructor(){}

@Input() selectFormControl : FormControl;
@Input() options : Object[];
@Input() OptionValue: any;
}

cdropdown.component.html

<mat-select [formControl]="selectFormControl" [placeholder]="placeholder">
  <mat-option *ngFor="let  option of options" [value]="option">
    {{option.optionvalue}}
  </mat-option>
</mat-select>

我正在为 mat-select 创建一个通用组件。因此我将选项的值作为 object 的列表传递。选项的键“optionvalue”可能不同。所以我想定义 mat-option.

应该使用什么键

现在我有了{{option.optionvalue}}。我必须使用@Input 从 parent 组件发送字符串 'optionvalue'。可否请指教

parent分量

options : object[] = [
 {
  key:1,
  optionValue:data1
 },
 {
  key:2,
  optionValue:data2
 }
]

**parent html **

<mat-dropdown [options]= "options" ></mat-dropdown>

如果要通过父组件传递 属性 以用作选项值,可以在模板中使用以下表达式 {{option[optionValue]}}

按如下方式传递 属性 字符串:

@Input() optionValue: string;

您可以 @Input 密钥名称。

Parent

.html

<mat-dropdown optionValue="optionvalue">

Child

.html

...
    {{option[optionValue]}}
...

.ts

@Input() optionValue: string;