javascriptangularangular-template

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


Solution

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