2017-12-02 7 views
1

私のコンポーネントは、テンプレート内にファンシーなHTMLを生成する外部ライブラリを読み込みます。図:外部ライブラリを動的にスタイリングする

@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); 
    } 
} 

ライブラリーは、<div id="square"/>をコンテナーの中に入れます。この正方形divの高さを変数dynamic_heightから動的に依存させるにはどうすればよいですか?単純なテンプレートコードの場合は、<div [style.height]="dynamic_height">とするだけです。しかし、HTMLはlibararyから来ているので、これは実現可能ではありません。

私のアイデア、これまで:スタイルで

  • #square { height: {{dynamic_height}} }。エラーはありませんがAngularはこれを解析しないので、明らかに無効なプロパティ値です。
  • テンプレート内:template: "<style>#square{ height: {{dynamic_height}} }</style>"。同じ
  • dynamic_height(ngOnChanges)の変更にフックし、document.getElementById("square").style.height = dynamic_heightを使用して手動で高さを更新します。うまくいくかもしれませんが、おそらく間違ったアプローチです。

ここでは、必要に応じてサンプルコードのプランナーを示します。 https://embed.plnkr.co/M46XfP/

(現実世界のユースケース:visタイムラインの設定、グループ高さ)

答えて

1

私はテンプレートに<style>タグを含むことになり、別のdivを作成することによって、それを行うために管理:その後

<div id="container" #container></div> 
<div id="styleContainer" #styleContainer></div> 

でapp.component.tsの場合は#styleContainerにデコレータ@ViewChildを使用し、HTMLを次のように挿入します。

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); 
    } 
} 

updateStyle()を呼び出すスタイルを変更するたびに、コンテナ内の<style>タグが置き換えられます。

updateStyle(height: string) { 
    this.style_container.nativeElement.innerHTML = 
    `<style>#square {height: `+height+` !important; }</style>`; 
} 
+0

は、プロパティの変更に自分自身を更新しないだろうが、これは私がプロパティを更新するために溶液で私の答えを編集し、それが最高のものではないかもしれませんが、それは働いていた邪悪なアイデア – Blauhirn

+0

です!コードは、ngOnInitのupdateStyleメソッドを呼び出して高さをパラメータとして与えることで簡略化できます –

関連する問題