如何在字符串中插入?

时间:2016-11-17 22:13:10

标签: angular interpolation

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

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

我的component.ts课程如下:

export class EditorsChoiceComponent {

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

2 个答案:

答案 0 :(得分:2)

使用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" />

答案 1 :(得分:1)

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

<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