首页 > 解决方案 > 如何在 Angular 中使用 @Input 将 mat-select 选项的键作为参数传递

问题描述

我想根据使用@Input 从父组件发送到子组件的字符串来显示 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 创建一个通用组件。所以我将选项的值作为对象列表传递。选项的键“optionvalue”可能不同。所以我想定义 mat-option 应该使用什么键。

现在我有了 {{option.optionvalue}}。我必须使用@Input 从父组件发送字符串'optionvalue'。是否可以请告知。

父组件

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

**父 html **

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

标签: angularangular-materialangular-library

解决方案


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

传递属性字符串如下:

@Input() optionValue: string;


推荐阅读