5

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

3 Answers 3

8

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, ...)

Sign up to request clarification or add additional context in comments.

5 Comments

mmm it's not good solution for me. I think that this logic must is put in template and not have a custom function.
why must you put logic in the template? moving code from template to component brings several benefits. if you don't like calling function on each render cycle, then you might recalculate the style whenewer value changes and store it in component property and use that property.
Why You Should Never Use Methods Inside Templates in Angular - betterprogramming.pub/…
If your view is based on your model and you model changes because of a method, this is just must better than calling a method, and probably get the same output as you did 5 seconds ago. MVC or MVX has this flow for a reason
never is too strong IMO ;), however i agree that it is a good practice to avoid calling function directly whenever possible, that's why i added the part about that.
1

I just want to drop here, that angular supports using javascript string-interpolation since 19.2.0 (untagged template literals).

Comments

0

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.

2 Comments

Feel free to check this other discussion - stackoverflow.com/questions/23302909/…
also the article, as far as I remember show pretty clear how to measure how many times your method in the template is being called, so the is not opinion based, it should be used carefully

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.