私が使用しているテンプレートのどこかにあるとしましょう:
<div *ng-for="#fooItem of foo">
{{fooItem.bar.baz.value}}
</div>
ループ内で毎回{{theBaz}}
使用するのではなく、次のようなものを記述できるようにしたいfooItem.bar.baz
と思います。それを達成する方法はありますか?多分任意の変数を定義することを可能にするいくつかの構文?
ドキュメントには、値を設定するコンポーネント/ディレクティブが、どうやら何も単純に伴う用途に言及しています。
考えられる解決策の1つは、小さなAngular2パイプを使用することです。
get-the-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>
`
})
ユースケースに応じて、これは良い考えかもしれませんし、そうでないかもしれません。
編集:さらに2つのソリューション
私が追加した以下のコードをチェックしてください:
(比較のために、アイテムソリューションに上記のパイプも含めました)
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);
サイズも試してみてください^
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加