Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a variable in an Angular 2 template?

Tags:

angular

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. 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.

like image 295
dgn Avatar asked Nov 16 '15 17:11

dgn


1 Answers

One possible solution would be with a small Angular2 Pipe.

get-the-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:

  1. piping on the list and,
  2. a good ol'fashioned function

(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^

like image 200
Ashley Coolman Avatar answered Oct 31 '22 20:10

Ashley Coolman