[英]Angular ngFor dynamic property
<mat-select placeholder="{{placeholder}}" [compareWith]="compareValues" (selectionChange)="selectionChanged($event)">
<mat-option #matOption *ngFor="let item of itemsList | async" [value]="item['{{value}}']">
{{item.Name}}
</mat-option>
</mat-select>
item['{{value}}'] item['{{value}}']
How to bind a dynamic property to ngFor.如何将动态属性绑定到 ngFor。 For example: I want to bind item.Name in one moment, but item.Value in different situations.例如:我想在某一时刻绑定 item.Name,但在不同情况下绑定 item.Value。
There are some more ways I guess, but I usually do the following:我猜还有更多方法,但我通常会执行以下操作:
<option *ngFor="let option of options; let i = index" [value]="option[this.field]">
Option {{i}}
</option>
this
keyword can be excluded in most versions of Angular, but may be not in older ones.大多数版本的 Angular 都可以排除this
关键字,但旧版本中可能不会。 Tested with Angular 6, and it works fine without this
keyword: [value]="option[field]"
.用 Angular 6 测试过,没有this
关键字也能正常工作: [value]="option[field]"
。
Pay attention, that you don't really need interpolation, here I just take an option
object and read the specific key, which is stored as a string in field
class property.请注意,您实际上并不需要插值,这里我只使用一个option
对象并读取特定键,该键以字符串形式存储在field
类属性中。 For example, if field
class property has a 'qwerty'
value, that part of HTML equals to [value]="option['qwerty']"
, and the binding will change when the value changes.例如,如果field
类属性具有'qwerty'
值,则 HTML 的该部分等于[value]="option['qwerty']"
,并且该值更改时绑定将更改。
Here is a working STACKBLITZ , you can check a console and ensure, that the binding changes dynamically.这是一个有效的STACKBLITZ ,您可以检查控制台并确保绑定动态更改。
如果您有一些变量告诉您何时要使用它们中的每一个,您可以创建一个条件,例如:
{{Item.UseName ? Item.Name : Item.Vaule }}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.