0

I'm looking for a way to set a local template variable who's value is provided by the component.

Component:

@Component({
  'my-component
})
@View({
  'templateUrl': '/templates/UserAnimals.html'
})
class UserAnimals {
  users : Object[];

  constructor() {
    this.users = [
      { _id: 0, name: 'John' },
      { _id: 1, name: 'Mary' },
    ];
  }

  getFavorite(userId : string) : Object {
    // return the animal object.
  }
}

Template:

<table>
  <tr *ngFor="#user of users"
      favoriteAnimal="getFavorite(user._id)">
    <!-- How do I do this? I'm looking for some way to set favoriteAnimal variable to 
     value from the component. After which favoriteAnimal is re-usable to all children
     of the tr tag. -->

    <td>
      {{ user.name }}
    </td>

    <td>
      {{ favoriteAnimal.type }}
    </td>

    <td>
      {{ favoriteAnimal.name }}
    </td>
  </tr>
</table>
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
vangorra
  • 1,631
  • 19
  • 24
  • You're making it extremely complicated. Just make the TR and TD a directive. That way TD can query for its parent (TD) and get the `favoriteAnimal`. – Eric Martinez Jan 24 '16 at 02:14
  • Please elaborate further. I'd like to hear more. – vangorra Jan 24 '16 at 06:09
  • Possible duplicate of [How to declare a variable in a template in Angular2](http://stackoverflow.com/questions/38582293/how-to-declare-a-variable-in-a-template-in-angular2) – Louis Mar 17 '17 at 12:06

1 Answers1

1

Instead of
{{ favoriteAnimal.type }} and {{ favoriteAnimal.name }} use
{{getFavorite(user._id).type}} and {{getFavorite(user._id).name}}.

I'm not aware of any way to set a local template variable like you describe.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • I considered such an approach but discredited it thinking the angular2 team would have come up with a more efficient solution. In angular1, this could be accomplished with ng-init. I'm curious why there isn't something like that for angular2. – vangorra Jan 23 '16 at 16:12
  • AFAIR `ng-init` was supposed to be only used for demo purposes but not for production. – Günter Zöchbauer Jan 23 '16 at 16:34