为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Angular中声明模板中的变量

如何在Angular中声明模板中的变量

慕森卡 2019-09-20 16:50:47
我有以下模板:<div>  <span>{{aVariable}}</span></div>并希望最终得到:<div "let a = aVariable">  <span>{{a}}</span></div>有办法吗?
查看完整描述

3 回答

?
猛跑小猪

TA贡献1858条经验 获得超8个赞


这在大多数情况下都有效,但它不是一般的解决方案,因为它依赖于变量的真实性


所以起源答案就像@Keith所说。这是另一种方法。我们可以像创建指令一样*ngIf调用它*ngVar


NG-var.directive.ts


@Directive({

    selector: '[ngVar]',

})

export class VarDirective {

  @Input()

  set ngVar(context: any) {

    this.context.$implicit = this.context.ngVar = context;

    this.updateView();

  }


  context: any = {};


  constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) {}


  updateView() {

    this.vcRef.clear();

    this.vcRef.createEmbeddedView(this.templateRef, this.context);

  }

}

使用此*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示例Angular4 ngVar


也可以看看


Angular 4在哪里为* ngIf定义“as local-var”行为?

起源

Angular v4


1)div+ ngIf+let


<div *ngIf="{ a: 1, b: 2 }; let variable">

  <span>{{variable.a}}</span>

  <span>{{variable.b}}</span>

</div>

2)div+ ngIf+as


视图


<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;

}

3)如果你不想像div你可以使用那样创建包装器ng-container


视图


<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>


查看完整回答
反对 回复 2019-09-20
?
慕莱坞森

TA贡献1810条经验 获得超4个赞

丑陋,但是:


<div *ngFor="let a of [aVariable]">

  <span>{{a}}</span>

</div>

与异步管道一起使用时:


<div *ngFor="let a of [aVariable | async]">

  <span>{{a.prop1}}</span>

  <span>{{a.prop2}}</span>

</div>


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 2052 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信