编程语言
首页 > 编程语言> > javascript – 如何使用es6模板文字作为角度组件输入

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

作者:互联网

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

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

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

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

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

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

但它不起作用:

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

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

解决方法:

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

这样你提供的方式很好.

<app-my-component [myInput]="'My name is ' + name + '!'"></app-my-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}!`;
}

在HTML中,

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

标签:template-literals,javascript,angular,typescript,ecmascript-6
来源: https://codeday.me/bug/20191006/1860884.html