如何在Angular2的模板中声明一个变量 [英] How to declare a variable in a template in Angular2
问题描述
我有以下模板:
< div>
< span> {{aVariable}}< / span>
< / div>
并希望最终结果为:
< divlet a = aVariable>
< span> {{a}}< / span>
< / div>
有没有办法做到?
update 3
问题2451在Angular 4.0.0中修复
$ b
另见
- https://github.com/angular/angular/pull/13297
- https://github.com/angular/angular/commit/b4db73d
- https://github.com/angular/angular/issues/13061
更新2
$ b 这不受支持。
有模板变量,但不支持分配任意值。它们只能用于引用它们所应用的元素,为 ngFor
,
另请参阅 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
- https://github.com/angular/angular/pull/13297
- https://github.com/angular/angular/commit/b4db73d
- https://github.com/angular/angular/issues/13061
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 theVarDirective
(exportAs: 'var'
)var="abc"
instantiates theVarDirective
and passes the string value"abc"
to it's value input.aVariable.var
reads the value assigned to thevar
directivesvar
input.
这篇关于如何在Angular2的模板中声明一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!