beachCode
beachCode

Reputation: 3500

Angular 2 dynamically changing directive properties in HTML

I'm using a component that contains a "widget" directive which currently includes some hard-coded variables in the component template. Something like this:

<widget image="{{imageUrl}}" [theme]="{color: blue, hue: '600'}"></widget>

Now I want to dynamically generate these directives and I'm not sure how to insert just the color from an array of colors. It would look something like this:

<div *ngFor='let user of _allusers; let rowIndex = index'>
   <widget image="{{imageUrl}}" [theme]="{color: colors[rowIndex], hue: '600'}"></widget>
</div>

Maybe I'm mistaken, but I don't think setting the entire "theme" string is the answer since the color changes as part of the template loop--not with some event/action in the component code. Can I do this in the component template, or do I need to change the directive?

Upvotes: 0

Views: 485

Answers (1)

yurzui
yurzui

Reputation: 214017

Possible you did something wrong in your code but this should work

template.html

<div *ngFor='let user of _allusers; let rowIndex = index'>
  <div>{{user.name}}</div>
  <widget [theme]="{ color: colors[rowIndex], hue: '600'}"></widget>
</div>

component.ts

colors = ['red', 'green', 'black']

Plunker Example

Upvotes: 1

Related Questions