如何将ES6模板字面量用作Angular组件输入

55

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

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

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

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

如果我可以使用ES6模板字面量(又称为模板字符串反引号字符串)就好了:

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

但是它并不起作用:

未捕获的错误:模板解析错误: 解析器错误:意外记号Lexer Error:在表达式中第1列的意外字符[`]

实现正确方式是什么?

3个回答

68

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 = 'Dinindu';
  this.input = `My name is ${this.name}!`;
}
在HTML中,
<app-my-component [myInput]="input"></app-my-component>

也可以这样使用。它非常接近于模板文字。

<app-my-component myInput="My name is {{name}}"></app-my-component>

5
还是这样吗?为什么会这样?我发现很奇怪,在2020年竟然还不支持。 - Pramus
3
因为它无法与内联模板一起使用,所以Angular团队拒绝了此请求 - https://github.com/angular/angular/issues/12914 - takrishna
1
到了2023年还是不行。不过在vuejs中可以正常工作 ;) - Edwin

34

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

myInput="My name is {{ name }}!"

你可以选择喜欢写哪个,但不幸的是反引号在绑定表达式中不被允许。


4
谢谢,我可以知道为什么不允许使用反引号吗? - Divek John
由于它无法与内联模板一起使用,因此Angular团队已拒绝了此请求- https://github.com/angular/angular/issues/12914。 - takrishna
1
你不能在{{ }}中使用模板字面量。 - serge

0

只要模板位于TS源代码而不是HTML中,使用模板文字表达式就可以工作。因此下面的方法不起作用。

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

但以下代码将会起作用

let displayString: String = 'I work in a string literal - ';

@Component({
  selector: 'app-product-alerts',
  template: `
    ${displayString} Tada !!
  `,
  styleUrls: ['./product-alerts.component.css']
})

如果您想探索实时代码,这里有一个示例: https://stackblitz.com/edit/angular-qpxkbd-urdema?file=src%2Fapp%2Fproduct-alerts%2Fproduct-alerts.component.ts


这仅适用于非常简单的情况。像 template: \<ul>${['banana', 'apple'].map(fruit=>`<li>${fruit}</li>`).join('')}</ul>`` 这样的东西将会失败。 - Sjeiti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接