How to use es6 template literal as Angular Compone

2020-03-01 05:40发布

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?

2条回答
Root(大扎)
2楼-- · 2020-03-01 06:03

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

This 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 = 'some name;
  this.input = `My name is ${this.name}!`;
}

In the HTML,

<app-my-component [myInput]="input"></app-my-component>
查看更多
太酷不给撩
3楼-- · 2020-03-01 06:15

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.

查看更多
登录 后发表回答