phil294
phil294

Reputation: 10852

Dynamically styling external library

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:

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

Answers (1)

br.julien
br.julien

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

Related Questions