我有以下模板:
<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>
有办法吗?
我们可以创建*ngIf
这样的指令,并将其命名为*ngVar
ng-var.directive.ts
@Directive({
select或: '[ngVar]',
})
exp或t class VarDirective {
@Input()
set ngVar(context: unknown) {
this.context.$implicit = this.context.ngVar = context;
if (!this.hasView) {
this.vcRef.createEmbeddedView(this.templateRef, this.context);
this.hasView = true;
}
}
private context: {
$implicit: unknown;
ngVar: unknown;
} = {
$implicit: null,
ngVar: null,
};
private hasView: boolean = false;
construct或(
private templateRef: TemplateRef<any>,
private vcRef: ViewContainerRef
) {}
}
有了这个*ngVar
指令,我们可以使用以下
<div *ngVar="false as variable">
<span>{{variable | json}}</span>
</div>
或
<div *ngVar="false; let variable">
<span>{{variable | json}}</span>
</div>
或
<div *ngVar="45 as variable">
<span>{{variable | json}}</span>
</div>
或
<div *ngVar="{ x: 4 } as variable">
<span>{{variable | json}}</span>
</div>
Plunker Example Angular4 ngVar
另见
Angular v4
div
+ngIf
+let
div
+ngIf
+as
view个
<div *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
<span>{{variable.c}}</span>
</div>
component.ts
exp或t class AppComponent {
x = 5;
}
div
这样的包装器,你可以使用ng-container
view个
<ng-container *ngIf="{ a: 1, b: 2, c: 3 + x } as variable">
<span>{{variable.a}}</span>
<span>{{variable.b}}</span>
<span>{{variable.c}}</span>
</ng-container>
正如@Keith在 comments 中提到的
this will w或k in most cases but it is not a general solution since it relies on variable being truthy
See update f或 another approach.
标记的情况下加入 HTML 中的段落