Reputation: 1982
I am trying to do something as follows, and I have no idea where to start looking it up even.
I am trying to create some object such as this
{
text: "hello {param1}",
param1: {
text:"world",
class: "bla"
}
}
The thing is I want to display it according to the text property like this:
<span> hello <span class="bla"> world </span></span>
Using a component for such thing won't really solve it - the only idea I have is using jquery, and I would like to avoid it. The text property format could be changed if it helps...
Upvotes: 0
Views: 4267
Reputation: 214007
I can suggest you an idea like this:
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'
}
};
}
See example in action here http://plnkr.co/edit/G5m7zAxzhybhN5QdnVik?p=preview
Upvotes: 2
Reputation: 139
One possible way could be like this : In your component class :
let myConfig = {
salutation : "hello",
paramText : "world",
paramClass : "bla"
}
And in your HTML :
<span> {{myConfig.salution}} <span class="{{myConfig.paramClass}}"> {{myConfig.paramText}} </span></span>
Then you could just swap the values of myConfig properties to generate text with the specified class for the paramText accordingly. Is this what you are looking for ?
Upvotes: 0