0

On Angular 7 I have the models:

export interface ProductModel {      
  files: FileModel[];
  name: string;     
}

export interface FileModel { 
  type: string;
  url: string;
}

On the template given a Product I need to display the url of the first file which type is "image":

{{ product.files.find(x => x.type == 'image').url }} 

But I get the error:

Bindings cannot contain assignments

How to do this?

Note

I am not sure product.files.find(x => x.type == 'image') returns any item.

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • You might want to use a variable instead of a method in your brackets. Then call a function (on init or on click) to change its value – Scott Picquerey Jul 09 '19 at 15:46
  • Possible duplicate of [Angular 2 - Bindings cannot contain assignments](https://stackoverflow.com/questions/43117917/angular-2-bindings-cannot-contain-assignments) – Heretic Monkey Jul 09 '19 at 15:48

3 Answers3

1

It is bad practice to use expressions in Angular bindings. I'd suggest moving your expression into a variable:

myItem: string = this.productModel.files.find(x => x.type == 'image').url;

And your html:

{{ myItem }} 

Take a look at this StackBlitz demonstration.

ViqMontana
  • 5,090
  • 3
  • 19
  • 54
  • this will cause an error in the case of there being no item in the files array with type image, which OP stated is possible... better off returning the actual item from the files array and binding like `{{ myItem?.url }}` – bryan60 Jul 09 '19 at 16:31
0

It's really a bad idea to do this in the first place. Every time change detection runs, this find call will be re-executed. This will drag the performance of your page down and might even become unusable. The preferred way is to assign a value to a property and bind to this property instead.

imageUrl : string;
findProd() {
  this.imageUrl =  product.files.find(x => x.type == 'image').url
}

and in template

{{ imageUrl }} 
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

In your code:

getProd() {
     return product.files.find(x => x.type == 'image').url
    }

template:

{{ getProd() }} 
xhasur
  • 1