Pasalino
Pasalino

Reputation: 1162

Angular String interpolation in attribute template

What is the best practice for string interpolation in attribute in Angular 6?

I have this code:

<div class="container" [ngStyle]="{'grid-template-rows': 'repeat(' + value + ', 1fr) [last-line]'}">

I want to use something like 'repeat(${value})' with backtick

Upvotes: 4

Views: 8738

Answers (2)

Ludevik
Ludevik

Reputation: 7254

You can move the functionality to your component and use backticks there:

calculateStyle(value: string): string {
   return `repeat(${value}, 1fr) [last-line]`;
}

and in template:

<div class="container" [ngStyle]="{'grid-template-rows': calculateStyle(value)}">

However you should try to avoid calling function from template whenever possible, so consider using some technique to avoid that (e.g. having observable remapped from an input, using state management, ...)

Upvotes: 6

Adam Cox
Adam Cox

Reputation: 3661

I came here looking for answer to the question, and while Mauricio expresses opinion based on article about using methods in templates, I think this is fine on a case-by-case basis. Hence, my upvote on the original answer.

However, I would like to build a string from logic in the template - like the question states. In my test on ver 14+, concatenating is possible with the double braces. For example:

<someComponent
  someProperty="{{someObj?.anotherProp}}{{someVar ? ' [TEST]' : null}}">
</someComponent>

Note the omission of the square brackets on the property name.

Upvotes: 0

Related Questions