Angular 11中如何为模板数据创建上下文
在Angular 11中实现块级数据上下文引用的方案
嘿,我懂你想要的那种简洁写法!Angular确实没有像Handlebars那样的{{#}}块级上下文语法,但我们有几种替代方案能达到同样的效果,不用反复写冗长的volunteer.personalData前缀。
方案1:用*ngIf创建局部变量(简单直接,适合单次使用)
如果只是想减少重复的前缀,这个方法最省事——我们利用*ngIf的特性,它不仅能做条件渲染,还能把赋值的变量暴露给当前作用域:
<div class="volunteer" *ngFor="let volunteer of volunteers"> <div class="personal-data"> <!-- 把personalData赋值给局部变量,条件设为true确保总是渲染 --> <ng-container *ngIf="volunteer.personalData as pd"> <h2>{{pd.firstName}} {{pd.lastName}}</h2> <p>{{pd.email}}</p> <p>{{pd.phone[pd.primaryPhone]}}</p> </ng-container> </div> </div>
这里我们把volunteer.personalData简写为pd,之后在容器内部就可以直接用pd.xxx来访问属性,比原写法简洁不少。
方案2:用<ng-template>和*ngTemplateOutlet实现完全上下文绑定(和你想要的写法一致)
如果你想完全实现像Handlebars那样直接引用属性名的效果,就可以用模板加上下文传递的方式:
<div class="volunteer" *ngFor="let volunteer of volunteers"> <div class="personal-data"> <!-- 引用定义好的模板,并传递personalData作为上下文 --> <ng-container *ngTemplateOutlet="personalDataTpl; context: volunteer.personalData" ></ng-container> </div> </div> <!-- 定义复用的模板,通过let-xxx="xxx"绑定上下文属性 --> <ng-template #personalDataTpl let-firstName="firstName" let-lastName="lastName" let-email="email" let-phone="phone" let-primaryPhone="primaryPhone" > <h2>{{firstName}} {{lastName}}</h2> <p>{{email}}</p> <p>{{phone[primaryPhone]}}</p> </ng-template>
这个方案里,模板内部可以直接用firstName、lastName这些变量,完全符合你想要的写法。如果这个模板需要在多个地方复用,这种方式会更灵活。
内容的提问来源于stack exchange,提问作者Jeremy Schultz
相关产品推荐
相关产品推荐

