如何插入字符串内?
什么是在以下情况下插入多个变量(来自一个类)的Angular2方法?如何插入字符串内?
<img alt="" src="/images/{{userName}}/{{year}}/{{nameOfImage}}.jpg" />
我component.ts
类看起来是这样的:
export class EditorsChoiceComponent {
userName = 'Black Ranger';
year = 'sometimeinthe90s';
nameOfImage = 'gogopowerrangers'
}
这是很容易使用template string做的类和accessor:
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" />
应工作,你已经拥有了它:
<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'
}
演示:
然后它只是一个带花括号的字符串,当然? – jonrsharpe
此解决方案给了我以下错误:'解析器错误:得到插值({{}}),其中表达式在列xx ...' – Moose
是的,只是试过了;同样在这里。不是我所期望的! – jonrsharpe
哦太好了!你能向我解释'get'是什么吗?我只是作为'{{imageSrc()}}'来访问它吗?为什么不是没有'get'写的方法? – Moose
@Moose'get'使它成为一个[访问器](http://www.typescriptlang.org/docs/handbook/classes.html#accessors) – jonrsharpe
如果你没有这个选项会怎么样,因为你的信息是通过循环。例如... '