Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use es6 template literal as Angular Component Input

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?

like image 421
Francesco Borzi Avatar asked Nov 01 '17 14:11

Francesco Borzi


People also ask

Are template literals ES6?

Template Literals is an ES6 feature (JavaScript 2015). Template Literals is not supported in Internet Explorer.

What are angular template literals?

Template Literals (formerly called "template strings" in prior drafts of the ECMAScript 6 language specification) are string literals providing intuitive expression interpolation for single-line and multiline strings.

Can I use JavaScript template literals?

The basic syntax of JavaScript template literalsUsing the backticks, you can freely use the single or double quotes in the template literal without escaping.

Is a template literal a string?

Template literals are sometimes informally called template strings, because they are used most commonly for string interpolation (to create strings by doing substitution of placeholders).


1 Answers

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> 
like image 143
dinindu Avatar answered Sep 30 '22 12:09

dinindu