我有以下模板:
<div>
<span>{{aVariable}}</span>
</div>
并希望以:
<div "let a = aVariable">
<span>{{a}}</span>
</div>
有办法吗?
我有以下模板:
<div>
<span>{{aVariable}}</span>
</div>
并希望以:
<div "let a = aVariable">
<span>{{a}}</span>
</div>
有办法吗?
当前回答
一个简单的解决方案可以满足我的需求:
<ng-container *ngIf="lineItem.productType as variable">
{{variable}}
</ng-container>
OR
<ng-container *ngIf="'ANY VALUE' as variable">
{{variable}}
</ng-container>
我使用的是Angular版本:12。这似乎也适用于其他版本。
其他回答
你可以使用Angular 2中的template元素或Angular 4+中的ng-template在html代码中声明变量。
模板有一个上下文对象,它的属性可以使用let绑定语法分配给变量。注意,您必须为模板指定一个出口,但它可以是对模板本身的引用。
<ng-template #selfie [ngTemplateOutlet]="selfie"
let-a="aVariable" [ngTemplateOutletContext]="{ aVariable: 123 }">
<div>
<span>{{a}}</span>
</div>
</ng-template>
<!-- Output
<div>
<span>123</span>
</div>
-->
您可以通过使用context对象的$implicit属性而不是自定义属性来减少代码量。
<ng-template #t [ngTemplateOutlet]="t"
let-a [ngTemplateOutletContext]="{ $implicit: 123 }">
<div>
<span>{{a}}</span>
</div>
</ng-template>
上下文对象可以是文字对象或任何其他绑定表达式。其他有效例子:
<!-- Use arbitrary binding expressions -->
<ng-template let-sum [ngTemplateOutletContext]="{ $implicit: 1 + 1 }">
<!-- Use pipes -->
<ng-template let-formatPi [ngTemplateOutletContext]="{ $implicit: 3.141592 | number:'3.1-5' }">
<!-- Use the result of a public method of your component -->
<ng-template let-root [ngTemplateOutletContext]="{ $implicit: sqrt(2116) }">
<!--
You can create an alias for a public property of your component:
anotherVariable: number = 123;
-->
<ng-template let-aliased [ngTemplateOutletContext]="{ $implicit: anotherVariable }">
<!--
The entire context object can be bound from a public property:
ctx: { first: number, second: string } = { first: 123, second: "etc" }
-->
<ng-template let-a="first" let-b="second" [ngTemplateOutletContext]="ctx">
它简单得多,不需要任何额外的东西。在我的例子中,我声明变量“open”,然后使用它。
<mat-accordion class="accord-align" #open>
<mat-expansion-panel hideToggle="true" (opened)="open.value=true" (closed)="open.value=false">
<mat-expansion-panel-header>
<span class="accord-title">Review Policy Summary</span>
<span class="spacer"></span>
<a *ngIf="!open.value" class="f-accent">SHOW</a>
<a *ngIf="open.value" class="f-accent">HIDE</a>
</mat-expansion-panel-header>
<mat-divider></mat-divider>
<!-- Quote Details Component -->
<quote-details [quote]="quote"></quote-details>
</mat-expansion-panel>
</mat-accordion>
如果你需要Angular语言服务中模板内部的自动补全支持:
同步:
myVar = { hello: '' };
<ng-container *ngIf="myVar; let var;">
{{var.hello}}
</ng-container>
使用async管道:
myVar$ = of({ hello: '' });
<ng-container *ngIf="myVar$ | async; let var;">
{{var.hello}}
</ng-container>
我的建议是:https://medium.com/@AustinMatherne/ angular-let-direcy-a168d4248138
这个指令允许你这样写:
<div *ngLet="'myVal' as myVar">
<span> {{ myVar }} </span>
</div>
在Angular 12中:
<div *ngIf="error$ | async as error">
<span class="text-warn">{{error.message}}</span>
</div>