【问题标题】:How to interpolate within a string?如何在字符串中插值?
【发布时间】:2016-11-17 22:13:10
【问题描述】:

在如下情况下插入多个变量(来自一个类)的 Angular2 方法是什么?

<img alt="" src="/images/{{userName}}/{{year}}/{{nameOfImage}}.jpg" />

我的component.ts 类如下所示:

export class EditorsChoiceComponent {

  userName = 'Black Ranger';
  year = 'sometimeinthe90s';
  nameOfImage = 'gogopowerrangers'
}

【问题讨论】:

    标签: angular interpolation


    【解决方案1】:

    在课堂上使用template stringaccessor 很容易做到这一点:

    export class EditorsChoiceComponent {
      userName = 'Black Ranger';
      year = 'sometimeinthe90s';
      nameOfImage = 'gogopowerrangers';
    
      get imageSrc() {
        return `/images/${this.userName}/${this.year}/${this.nameOfImage}.jpg`;
      }
    }
    

    绑定可以是简单的property binding而不是插值:

    <img alt="" [src]="imageSrc" />
    

    【讨论】:

    • 哦,太好了!你能解释一下get 的作用吗?我只是以{{ imageSrc() }} 的身份访问它吗?为什么不写没有get的方法?
    • @Moose get 使其成为accessor
    • 如果您没有该选项怎么办,因为您的信息是通过循环动态注入的。例如...&lt;form [formGroup]="foo_bar"&gt; &lt;div formGroupName="baz_{{$i}}" *ngFor="let foo of things; let $i = index"&gt; &lt;input [class.bar]="!foo_bar.get('baz_{{$i}}').valid"&gt; &lt;/input&gt; &lt;/div&gt; &lt;/form&gt; 在预期表达式的位置返回插值。
    • @CalebSwank 为什么不让循环中的每个项目都由知道自己索引的组件呈现? &lt;form [formGroup]="foo_bar"&gt; &lt;my-component *ngFor="let foo of things; let $i = index" [data]="foo" [index]="$i"&gt;&lt;/my-component&gt;&lt;/form&gt;.
    • @johnrsharpe 只是在试错过程中偶然发现了这一点,但通过我的场景,一个简单的实现将是这样的。 ('baz_' + $i) - 我什至没有想到。不过感谢您的帮助。这可能也可以在上述情况下类似地实现。
    【解决方案2】:

    应该像你已经拥有的那样工作:

    <img alt="" src="/images/{{userName}}/{{year}}/{{nameOfImage}}.jpg" />
    

    例子:

    @Component({
      selector: 'blue',
      template: 'Hello <img src="https://{{server}}/{{path}}" />'
    })
    export class BlueComponent { 
      server:string='encrypted-tbn3.gstatic.com'
      path: string='images?q=tbn:ANd9GcShusMbGevCg9avhj28vFlBQsUlv49OFoXWUDyHmZOawWZUEm0L0TSB526d'
    
    }
    

    演示:

    http://plnkr.co/edit/VOMYCN3sLMsqZQxn1jAJ?p=preview

    【讨论】:

    • 那么它只是一个带有花括号的文字字符串,确定吗?
    • 这个解决方案给了我以下错误:Parser Error: Got interpolation ({{}}) where expression was expected at column xx...
    • 是的,刚刚试过;同样在这里。和我预期的不太一样!
    猜你喜欢
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2021-09-28
    • 2018-01-06
    相关资源
    最近更新 更多