首页 > 解决方案 > 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.

标签: angular

解决方案


一种解决方案是将结果保存到模板变量中,使用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


推荐阅读