Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Angular's "as" without *ngIf? [duplicate]

Tags:

html

angular

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 ?

like image 719
Scipion Avatar asked Jul 26 '16 06:07

Scipion


1 Answers

Update

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

  • Where does Angular 4 define "as local-var" behavior for *ngIf?

Original answer

Angular v4

  1. div + ngIf + let

    {{variable.a}} {{variable.b}}
  2. 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;
}
  1. If you don't want to create wrapper like 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.

like image 127
yurzui Avatar answered Oct 29 '22 09:10

yurzui