【问题标题】:How to use es6 template literal as Angular Component Input如何使用 es6 模板文字作为 Angular 组件输入
【发布时间】:2018-04-13 22:30:57
【问题描述】:

在我的 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>

但它不起作用:

未捕获的错误:模板解析错误: 解析器错误:意外的标记词法分析器错误:表达式中第 1 列的意外字符 [`]

实现它的正确方法是什么?

【问题讨论】:

    标签: javascript angular typescript ecmascript-6 template-literals


    【解决方案1】:

    ES6 Template literals (Template strings) 不能在 Angular 组件输入中使用,因为 Angular compiler 不知道这个语法。

    你提供的方式很好。

    <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>
    

    【讨论】:

    • 还是这样吗?这是什么原因?我觉得很奇怪,到了 2020 年它仍然不受支持。
    • 因为它不适用于内联模板 - 此请求已被 Angular 团队拒绝 - github.com/angular/angular/issues/12914
    【解决方案2】:

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

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

    你喜欢写哪个取决于你,但不幸的是,绑定表达式中不允许使用反引号。

    【讨论】:

    【解决方案3】:

    只要模板存在于 TS 源而不是 HTML 中,就可以使用模板文字表达式。所以以下不起作用

    &lt;app-my-component [myInput]="`My name is ${name}!`"&gt;&lt;/app-my-component&gt;

    但是下面的会起作用

    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: `&lt;ul&gt;${['banana', 'apple'].map(fruit=&gt;`&lt;li&gt;${fruit}&lt;/li&gt;`).join('')}&lt;/ul&gt;` 这样的东西会失败。
    猜你喜欢
    • 2017-07-30
    • 2016-04-16
    • 1970-01-01
    • 2021-01-10
    • 2016-10-15
    • 2014-10-08
    • 2014-08-04
    • 2019-01-17
    • 1970-01-01
    相关资源
    最近更新 更多