如何使用es6模板文字作为角度组件输入

Fra*_*rzi 13 javascript typescript ecmascript-6 template-literals angular

在我的Angular 4应用程序中,我有一个接受字符串输入的组件:

<app-my-component [myInput]="'some string value'"></app-my-component>
Run Code Online (Sandbox Code Playgroud)

在某些情况下,我需要在字符串中传递一个变量,例如:

<app-my-component [myInput]="'My name is ' + name + '!'"></app-my-component>
Run Code Online (Sandbox Code Playgroud)

如果我可以使用es6模板文字(也就是模板字符串反向标记字符串)会很好:

<app-my-component [myInput]="`My name is ${name}!`"></app-my-component>
Run Code Online (Sandbox Code Playgroud)

但它不起作用:

未捕获错误:模板解析错误:分析器错误:意外的令牌Lexer错误:表达式中第1列的意外字符[`]

完成它的正确方法是什么?

din*_*ndu 17

ES6模板文字不能在Angular组件输入中使用,因为angular编译器不知道这个语法.

这样你提供的方式很好.

<app-my-component [myInput]="'My name is ' + name + '!'"></app-my-component>
Run Code Online (Sandbox Code Playgroud)

或类似的东西,

在组件中,

// 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}!`;
}
Run Code Online (Sandbox Code Playgroud)

在HTML中,

<app-my-component [myInput]="input"></app-my-component>
Run Code Online (Sandbox Code Playgroud)

  • 因为它不适用于内联模板 - 此请求已被 Angular 团队拒绝 - https://github.com/angular/angular/issues/12914 (3认同)
  • 现在还是这样吗?这是什么原因呢?我觉得很奇怪,到了2020年了仍然不支持。 (2认同)

Exp*_*lls 10

您仍然可以在属性值中使用angular的插值语法:

myInput="My name is {{ name }}!"
Run Code Online (Sandbox Code Playgroud)

这取决于您喜欢编写的内容,但遗憾的是,绑定表达式中不允许使用反引号.

  • 谢谢,请问为什么不允许反引号 (2认同)