[英]How to define a variable in an Angular 2 template?
Let's say that somewhere in my template I'm using: 让我们说我正在使用的模板中的某处:
<div *ng-for="#fooItem of foo">
{{fooItem.bar.baz.value}}
</div>
I would like to be able to write something like {{theBaz}}
instead of using fooItem.bar.baz
every time in my loop. 我希望能够在我的循环中编写类似
{{theBaz}}
而不是使用fooItem.bar.baz
。 Is there a way to achieve that? 有没有办法实现这一目标? Maybe some syntax that allows to define arbitrary variables?
也许某些语法允许定义任意变量?
The documentation mentions usages that involve components/directives setting the value, but apparently nothing simpler. 文档提到了涉及组件/指令设置值的用法,但显然没什么比这更简单的了。
One possible solution would be with a small Angular2 Pipe . 一种可能的解决方案是使用小型Angular2管道 。
get-the-baz.ts: 获得最baz.ts:
import {Pipe} from 'angular2/angular2';
@Pipe({
name: 'theBaz'
})
export class GetTheBaz {
transform(item) {
return item.bar.baz.value
}
}
And in your app: 在你的应用程序中:
import {Component, bootstrap, NgFor} from 'angular2/angular2';
import {GetTheBaz} from './get-the-baz';
@Component({
selector: 'my-app',
directives: [NgFor],
pipes: [GetTheBaz],
template: `QuickApp:
<div *ng-for="#item of list">
{{item|theBaz}}
</div>
`
})
Depending on your use case, this may or may not be a good idea. 根据您的使用情况,这可能是也可能不是一个好主意。
EDIT: Two more solutions 编辑:另外两个解决方案
Check out the code below I have added: 看看我添加的以下代码:
(I also included the above pipe on an item solution for comparison) (我还在项目解决方案中包含了上述管道以供比较)
import {Component, bootstrap, NgFor} from 'angular2/angular2';
import {Pipe} from 'angular2/angular2';
// This may not be the most efficient way, I'll do some research and edit in a moment
var _getC = val => (val && val['a'] && val.a['b'] ) ? val.a.b['c'] : null;
@Pipe({
name: 'pipeC'
})
export class pipeC {
transform(val) {
return _getC(val)
}
}
@Pipe({
name: 'pipeCFromList'
})
export class pipeCFromList {
transform(list) {
return list.map(_getC);
}
}
@Component({
selector: 'my-app',
directives: [NgFor],
pipes: [pipeC, pipeCFromList],
template: `QuickApp:
<p>pipe item:</p>
<div *ng-for="#item of list">
<item [text-content]="item|pipeC"> </item>
</div>
<p>pipe list:</p>
<div *ng-for="#num of list|pipeCFromList">
<item [text-content]="num"> </item>
</div>
<p>func item:</p>
<div *ng-for="#item of list">
<item [text-content]="getC(item)"> </item>
</div>
`
})
class AppComponent {
public getC (val) {
return _getC(val);
};
list = [{a:{b:{c:1}}}]
}
bootstrap(AppComponent);
Try these on for size as well^ 尝试这些也是为了大小^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.