我正在尝试执行以下操作,甚至我不知道从哪里开始查找它。
我正在尝试创建一些这样的对象
{
text: "hello {param1}",
param1: {
text:"world",
class: "bla"
}
}
问题是我想根据文本属性显示它,如下所示:
<span> hello <span class="bla"> world </span></span>
为这样的事情使用组件并不能真正解决它 - 我唯一的想法是使用 jquery,我想避免它。如果文本属性格式有帮助,可以更改...
我可以向你推荐这样的想法:
import { Component, Directive, Input, HostBinding } from '@angular/core'
@Directive({
selector: 'my-template'
})
class MyTemplate {
@Input() data: Object;
@HostBinding('innerHTML') get html {
return Object.keys(this.data).reduce((prev, cur) => {
if(cur === 'text') return prev;
const regExp = new RegExp(`{${cur}}`, 'g');
return prev.replace(regExp, (str) =>{
return `<${this.data[cur].tag} class="${this.data[cur].class}">
${this.data[cur].text}
</${this.data[cur].tag}>`;
});
}, this.data.text);
}
}
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<my-template [data]="obj"></my-template>
</div>
`,
directives: [MyTemplate]
})
export class App {
obj = {
text: "hello {param1} {param2} please again hello {param1}",
param1: {
tag: 'span',
text: 'world',
class: 'bla'
},
param2: {
tag: 'div',
text: 'hello world2',
class: 'bla'
}
};
}
在此处查看实际示例 http://plnkr.co/edit/G5m7zAxzhybhN5QdnVik?p=preview
一种可能的方法可能是这样的:在您的组件类中:
let myConfig = {
salutation : "hello",
paramText : "world",
paramClass : "bla"
}
在你的 HTML 中:
<span> {{myConfig.salution}} <span class="{{myConfig.paramClass}}"> {{myConfig.paramText}} </span></span>
然后,您可以交换 myConfig 属性的值,以相应地生成具有参数文本的指定类的文本。这是你要找的吗?