Reputation: 10852
My component loads an external library which generates some fancy HTML inside the template. Illustration:
@Component({
template: `<div #container></div>`,
encapsulation: ViewEncapsulation.None,
export class App {
@ViewChild("container") container_ref;
dynamic_height = "50 px";
ngOnInit() {
The_library.insert_html_square_inside_of(this.container_ref.nativeElement);
}
}
The library puts a <div id="square"/>
inside the container. How do I make this square div's height dynamically dependent from my dynamic_height
variable? If it were simple template code, I could just do <div [style.height]="dynamic_height">
. But the html is comes from the libarary, so this is not feasible.
My ideas so far:
#square { height: {{dynamic_height}} }
. No error but Angular does not parse this, thus obviously invalid property value.template: "<style>#square{ height: {{dynamic_height}} }</style>"
. Samedynamic_height
(ngOnChanges) and updating the height manually using document.getElementById("square").style.height = dynamic_height
. Might work, but is probably the wrong approach.Here is a plunker with sample code, if desired. https://embed.plnkr.co/M46XfP/
(real world use case: setting group height of vis
timeline)
Upvotes: 1
Views: 159
Reputation: 3460
I managed to do it by creating another div which would contain the <style>
tag in the template :
<div id="container" #container></div>
<div id="styleContainer" #styleContainer></div>
Then in app.component.ts, you use the decorator @ViewChild
for #styleContainer and you insert the HTML this way :
export class App {
@ViewChild("container") container_ref;
@ViewChild("styleContainer") style_container;
dynamic_height = '50px';
ngOnInit() {
render_something(this.container_ref.nativeElement);
this.updateStyle(this.dynamic_height);
}
}
Each time you want to change the style you call updateStyle() and it will replace the <style>
tag in the container.
updateStyle(height: string) {
this.style_container.nativeElement.innerHTML =
`<style>#square {height: `+height+` !important; }</style>`;
}
Upvotes: 1