angular - Angular - pass variable to HTML
问题描述
I have the HTML
<mat-card *ngFor="let shift of employer.shifts">
<mat-card-content>
<div *ngIf="getShiftLocation(shift);">
<div>{{ getShiftLocation(shift)['title'] }}</div>
<div>{{ getShiftLocation(shift)['phone'] }}</div>
<div>{{ getShiftLocation(shift)['manager'] }}</div>
</div>
</mat-card-content>
</mat-card>
There's the function getShiftLocation(shift) which returns Location object's field value
The question is: is there any way to set the whole Location object in this HTML in order I could use it?
For example:
<pre>
<div #location="getShiftLocation(shift)">
<div>{{location.title}}</div>
</div>
</pre>
Maybe the other way as well.
解决方案
一种解决方案是将结果保存到模板变量中,使用ngIf
指令的语法糖,它看起来像:
<mat-card *ngFor="let shift of employer.shifts">
<mat-card-content>
<div *ngIf="getShiftLocation(shift) as shiftLocation">
<div>{{ shiftLocation.title }}</div>
<div>{{ shiftLocation.phone }}</div>
<div>{{ shiftLocation.manager }}</div>
</div>
</mat-card-content>
</mat-card>
但请记住,该方法最终会在每个变化检测循环中被调用,因此不要在其中进行复杂的计算或 CPU 密集型任务。
注意:当 Angular 应该重用 DOM 元素时,您还应该使用指令的trackBy
功能来更好地控制。ngForOf
推荐阅读
- mysql - 我没有得到正确的 MySQL 表是通过组合另外两个表的键创建的如何加入它们
- elixir - 通过 Plug.Conn.send_file 提供 SPA
- qt - 检查后代在 QML 中是否具有 activeFocus == true
- node.js - 我应该如何从另一个集合中获取数据并加入结果
- php - 我可以从 android webview 打开 whatsapp 应用程序吗
- python - 安装 Scrapy 时出现扭曲设置错误
- java - 如何在根据其他实例变量的值不断更新的类中设置实例变量?
- java - 如何根据实际方向使用不同的片段?
- java - 树切割问题:删除数组列表元素而不破坏顺序
- java - 如何在给定 Activity 参数的静态方法中使用超类?