Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  122] [ 2]  / answers: 1 / hits: 47919  / 7 Years ago, wed, november 1, 2017, 12:00:00

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?


More From » angular

 Answers
9

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>

[#56045] Sunday, October 29, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;