Reputation: 1714
I have an Angular application which loads a configuration .json
file. Essentially what I am trying to do is dynamically select components and add inline styles to the element.
config is given below as an example of the config structure fetched from a http request.
For example;
var config = [
{
name: "header-component",
styles: "margin:0;padding:0;background:black"
}
]
<div *ngFor="let conf of config">
<{{conf.name}} style="{{conf.styles}}"></{{conf.name}}>
</div>
Any idea's on getting this to work or an alternative approach?
Upvotes: 0
Views: 359
Reputation: 41427
angular don't bind var
variables to dom. Use it like this
config :{ name: string, styles: string }[]= [
{
name: "header-component",
styles: "margin:0;padding:0;background:black"
}
]
updated
you can create a @pipe
and bind the html. modify the json like this.
config :{ name: string, styles: string, html : string }[]= [
{
name: "header-component",
styles: "margin:0;padding:0;background:black",
html : "<{{conf.name}} ngStyle='[conf.styles]'></{{conf.name}}>"
}
]
add this pipe to your code
@Pipe({name: 'safeHtml'})
export class Safe {
constructor(private sanitizer:Sanitizer){}
transform(style) {
return this.sanitizer.bypassSecurityTrustStyle(style);
// return this.sanitizer.bypassSecurityTrustHtml(style);
// return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
}
}
call the pipe in the html
<div *ngFor="let conf of config">
<div [innerHTML]="conf.html | safeHtml"></div>
</div>
Upvotes: 1