我有以下模板:
<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>
有办法吗?
当前回答
它简单得多,不需要任何额外的东西。在我的例子中,我声明变量“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>
其他回答
丑,但是:
<div *ngFor="let a of [aVariable]">
<span>{{a}}</span>
</div>
当与async管道一起使用时:
<div *ngFor="let a of [aVariable | async]">
<span>{{a.prop1}}</span>
<span>{{a.prop2}}</span>
</div>
下面是我编写的一个指令,它扩展了exportAs装饰器参数的使用,并允许您使用字典作为局部变量。
import { Directive, Input } from "@angular/core";
@Directive({
selector:"[localVariables]",
exportAs:"localVariables"
})
export class LocalVariables {
@Input("localVariables") set localVariables( struct: any ) {
if ( typeof struct === "object" ) {
for( var variableName in struct ) {
this[variableName] = struct[variableName];
}
}
}
constructor( ) {
}
}
你可以在模板中使用它:
<div #local="localVariables" [localVariables]="{a: 1, b: 2, c: 3+2}">
<span>a = {{local.a}}</span>
<span>b = {{local.b}}</span>
<span>c = {{local.c}}</span>
</div>
当然,#local可以是任何有效的局部变量名。
在Angular 12中:
<div *ngIf="error$ | async as error">
<span class="text-warn">{{error.message}}</span>
</div>
如果你需要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>
像这样试试
<ng-container
[ngTemplateOutlet]="foo"
[ngTemplateOutletContext]="{ test: 'Test' }"
></ng-container>
<ng-template #foo let-test="test">
<div>{{ test }}</div>
</ng-template>