typescript 如何使用 es6 模板文字作为 Angular 组件输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47057696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use es6 template literal as Angular Component Input
提问by Francesco Borzi
In my Angular 4 application, I have a component which takes a string input:
在我的 Angular 4 应用程序中,我有一个接受字符串输入的组件:
<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 stringsor back-tick strings):
如果我可以使用es6 模板文字(又名模板字符串或反引号字符串),那就太好了:
<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
未捕获的错误:模板解析错误:解析器错误:意外的标记词法分析器错误:表达式中第 1 列的意外字符 [`]
What's the correct way to accomplish it?
实现它的正确方法是什么?
回答by dinindu
ES6 Template literals (Template strings)cannot be used inside an Angular component input, because the Angular compilerdoesn't know this grammar.
ES6 模板文字(模板字符串)不能在 Angular 组件输入中使用,因为Angular 编译器不知道这种语法。
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,
在 HTML 中,
<app-my-component [myInput]="input"></app-my-component>
Update
更新
Also can use it as this way,
也可以这样使用,
<app-my-component myInput="My name is {{name}}"></app-my-component>
回答by Explosion Pills
You can still use angular's interpolation syntax in attribute values:
您仍然可以在属性值中使用 angular 的插值语法:
myInput="My name is {{ name }}!"
It's up to you which you prefer to write, but unfortunately backticks are not allowed in binding expressions.
由您决定您喜欢编写哪个,但不幸的是,绑定表达式中不允许使用反引号。