I have the following template :
<div>
<span>{{aVariable}}</span>
</div>
and would like to end up with :
<div "let a = aVariable">
<span>{{a}}</span>
</div>
Is there a way to do it ?
We can just create directive like *ngIf
and call it *ngVar
ng-var.directive.ts
@Directive({
selector: '[ngVar]',
})
export 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;
constructor(
private templateRef: TemplateRef<any>,
private vcRef: ViewContainerRef
) {}
}
with this *ngVar
directive we can use the following
<div *ngVar="false as variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="false; let variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="45 as variable">
<span>{{variable | json}}</span>
</div>
or
<div *ngVar="{ x: 4 } as variable">
<span>{{variable | json}}</span>
</div>
Plunker Example Angular4 ngVar
See also
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
export class AppComponent {
x = 5;
}
div
you can use 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>
As @Keith mentioned in comments
this will work in most cases but it is not a general solution since it relies on variable being truthy
See update for another approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With