最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular String interpolation in attribute template - Stack Overflow

programmeradmin0浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论