admin管理员组

文章数量:1333451

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

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

Share Improve this question edited May 27, 2022 at 14:46 Vadim Ovchinnikov 14k7 gold badges65 silver badges94 bronze badges asked Sep 21, 2018 at 11:17 PasalinoPasalino 1,1721 gold badge10 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can move the functionality to your ponent 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, ...)

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.

本文标签: javascriptAngular String interpolation in attribute templateStack Overflow