How to use es6 template literal as Angular Component Input

33,115

Solution 1

ES6 Template literals (Template strings) cannot be used inside an Angular component input, because the Angular compiler doesn't know this grammar.

The way that you provided is fine.

<app-my-component [myInput]="'My name is ' + name + '!'"></app-my-component>

Or something like this,

In the component,

// In the component, you can use ES6 template literal
name: string;
input: string;
    
ngOnInit() {
  this.name = 'Dinindu';
  this.input = `My name is ${this.name}!`;
}

In the HTML,

<app-my-component [myInput]="input"></app-my-component>

Also can use it as this way. Its really close to template literal,

<app-my-component myInput="My name is {{name}}"></app-my-component>

Solution 2

You can still use angular's interpolation syntax in attribute values:

myInput="My name is {{ name }}!"

It's up to you which you prefer to write, but unfortunately backticks are not allowed in binding expressions.

Share:
33,115
Francesco Borzi
Author by

Francesco Borzi

https://github.com/FrancescoBorzi

Updated on July 09, 2022

Comments

  • Francesco Borzi
    Francesco Borzi almost 2 years

    In my Angular 4 application, I have a component which takes a string input:

    <app-my-component [myInput]="'some string value'"></app-my-component>
    

    In some cases I need to pass a variable inside the string, for example:

    <app-my-component [myInput]="'My name is ' + name + '!'"></app-my-component>
    

    it would be nice if I could use es6 template literals (aka template strings or back-tick strings):

    <app-my-component [myInput]="`My name is ${name}!`"></app-my-component>
    

    but it doesn't work:

    Uncaught Error: Template parse errors: Parser Error: Unexpected token Lexer Error: Unexpected character [`] at column 1 in expression

    What's the correct way to accomplish it?

  • Pramus
    Pramus about 4 years
    Is it still the case? What's the reason for that? I find it very strange that in 2020 it's still not supported.
  • Divek John
    Divek John over 3 years
    Thank you, may I know why backticks are not allowed
  • takrishna
    takrishna almost 3 years
    Because it would not work with inline templates - this request has been rejected by Angular team - github.com/angular/angular/issues/12914
  • takrishna
    takrishna almost 3 years
    Because it would not work with inline templates - this request has been rejected by Angular team - github.com/angular/angular/issues/12914
  • Sjeiti
    Sjeiti over 2 years
    This only works for very simple things. Something like template: `<ul>${['banana', 'apple'].map(fruit=>`<li>${fruit}</li>`).join('')}</ul>` will fail.
  • serge
    serge about 2 years
    you can't use the template literal inside {{ }}