如何在 Angular 2 模板中定义变量?

How to define a variable in an Angular 2 template?

假设我正在使用的模板中的某处:

<div *ng-for="#fooItem of foo">
    {{fooItem.bar.baz.value}}
</div>

我希望能够编写类似 {{theBaz}} 的内容,而不是每次在我的循环中都使用 fooItem.bar.baz。有没有办法做到这一点?也许一些允许定义任意变量的语法?

documentation 提到了涉及 components/directives 设置值的用法,但显然没有更简单的。

一个可能的解决方案是 Angular2 Pipe

获取-baz.ts:

import {Pipe} from 'angular2/angular2';

@Pipe({
    name: 'theBaz'
})

export class GetTheBaz {
    transform(item) {
        return item.bar.baz.value
    }
}

在您的应用中:

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>
    `
})

根据您的用例,这可能是个好主意,也可能不是。

编辑:另外两个解决方案

查看下面我添加的代码:

  1. 管道在列表中,
  2. 一个很好的老式函数

(我也把上面的管道放在了一个item的解决方案中进行比较)

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

也可以试穿这些尺码^