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)
Exp*_*lls 10
您仍然可以在属性值中使用angular的插值语法:
myInput="My name is {{ name }}!"
Run Code Online (Sandbox Code Playgroud)
这取决于您喜欢编写的内容,但遗憾的是,绑定表达式中不允许使用反引号.