如何在Angular2的模板中声明一个变量 [英] How to declare a variable in a template in Angular2

查看:83
本文介绍了如何在Angular2的模板中声明一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模板:

 < div> 
< span> {{aVariable}}< / span>
< / div>

并希望最终结果为:

 < divlet a = aVariable> 
< span> {{a}}< / span>
< / div>

有没有办法做到?

解决方案

update 3



问题2451在Angular 4.0.0中修复


$ b

另见



更新2
$ b 这不受支持。

有模板变量,但不支持分配任意值。它们只能用于引用它们所应用的元素,为 ngFor

$ b $等结构指令导出指令或组件的名称和范围变量b

另请参阅 https://github.com/angular/angular/issues / 2451



更新1

  @Directive({
selector:'[var]',
exportAs:'var'
})$ b $ class VarDirective {
@Input() VAR:任;
}

并初始化它就像

 < div#aVariable =varvar =abc>< / div> 

 < div#aVariable =var[var] ='abc'>< / div> 

并使用变量如

 < DIV> {{aVariable.var}}< / DIV> 

(未经测试)


  • #aVariable 创建对 VarDirective 的引用( exportAs:'var '

  • var =abc实例化 VarDirective ,并将字符串值abc传递给它的值输入
  • aVariable.var 读取分配给 var 指令 var 输入的值。


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 ?

解决方案

update 3

Issue 2451 is fixed in Angular 4.0.0

See also

update 2

This isn't supported.

There are template variables but it's not supported to assign arbitrary values. They can only be used to refer to the elements they are applied to, exported names of directives or components and scope variables for structural directives like ngFor,

See also https://github.com/angular/angular/issues/2451

Update 1

@Directive({
  selector: '[var]',
  exportAs: 'var'
})
class VarDirective {
  @Input() var:any;
}

and initialize it like

<div #aVariable="var" var="abc"></div>

or

<div #aVariable="var" [var]="'abc'"></div>

and use the variable like

<div>{{aVariable.var}}</div>

(not tested)

  • #aVariable creates a reference to the VarDirective (exportAs: 'var')
  • var="abc" instantiates the VarDirective and passes the string value "abc" to it's value input.
  • aVariable.var reads the value assigned to the var directives var input.

这篇关于如何在Angular2的模板中声明一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆