让我们说我正在使用的模板中的某处:
<div *ng-for="#fooItem of foo">
{{fooItem.bar.baz.value}}
</div>
Run Code Online (Sandbox Code Playgroud)
我希望能够在循环中编写类似的东西,{{theBaz}}而不是fooItem.bar.baz每次都使用.有没有办法实现这一目标?也许某些语法允许定义任意变量?
该文件提到,涉及部件/指令设定值,但显然没有什么简单的用法.
一种可能的解决方案是使用小型Angular2 Pipe。
获取 baz.ts:
import {Pipe} from 'angular2/angular2';
@Pipe({
name: 'theBaz'
})
export class GetTheBaz {
transform(item) {
return item.bar.baz.value
}
}
Run Code Online (Sandbox Code Playgroud)
在你的应用程序中:
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>
`
})
Run Code Online (Sandbox Code Playgroud)
根据您的用例,这可能是也可能不是一个好主意。
编辑:另外两个解决方案
查看我添加的下面的代码:
(我还在项目解决方案中包含了上述管道以进行比较)
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);
Run Code Online (Sandbox Code Playgroud)
也试穿一下尺寸^
| 归档时间: |
|
| 查看次数: |
8813 次 |
| 最近记录: |