2

is this type of syntax valid?

<img [src]="someImg + (i + 1) ? someImg + (i + 1)  : ''" alt="{{ someName }}" />

if not, how can I dynamically add a variable to the image src on each iteration of the ngFor loop?. The code above gives me the variable i'm trying to get data from but not the data.

the data i'm trying to get data from is only 3 variables. someImg1, someImg2, someImg3

I have also tried this code syntax too.

 <img src="{{someImg + (i + 1)}} ? {{someImg + (i + 1)}}  : ''" alt="{{ someName }}" />

I even tried this one too.

<img [src]="someImg + (i + 1)" />

and

<img src="{{someImg + (i + 1)}}" />

any suggestions?

Austin752
  • 29
  • 8

3 Answers3

1

There are two ways to access properties of an object:

Dot notation: something.bar
Bracket notation: something['bar']

The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:

var foo = 'bar';
something[foo];

In your code someImg1 is a property name of current object (this), you can access it by

<img [src]="this['someImg' + (i + 1)]" />

I made an demo here: https://stackblitz.com/edit/angular-display-dynamic-property

More reference about Dynamically access object property using variable at Dynamically access object property using variable

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
  • thank you at was exactly what I was looking for. I didn't know you could use this in the component template. That helps me a lot! – Austin752 Apr 24 '19 at 15:42
0

You can use a function to get the image path like so:

<img [src]="getImagePath(i + 1)" alt="{{ someName }}" />

And in your ts file:

public getImagePath(index) {
    return this.someImage && this.someImage[index] ? this.someImage[index] : ''
}

And if you don't wanna display the image at all you can bind the function call to a parent div and add an ngIf like so:

<div *ngIf="getImagePath(i + 1) as imagePath">
  <img [src]="imagePath" alt="{{ imagePath }}" />
</div> 
Nadhir Falta
  • 5,047
  • 2
  • 21
  • 43
-2

Property name concatenation doesn't work the way you're trying, it adds to the value of the property rather than the name. To modify the name, you have to use square bracket notation and make the property name a string instead:

[src]="this['someImg' + (i + 1)] || ''"

(I also replaced the ternary expression with a short-circuit OR to make it less cumbersome)

John Montgomery
  • 6,739
  • 9
  • 52
  • 68