2017-07-18 26 views
3

我有一個角1個應用程序,我使用:angular.element替代起

let css = ".toolbar-background {background-color: #D3300E !important;}"; 

angular.element(document.body).append(angular.element('<div><style>' + css + '</style></div>')); 

我遷移我的應用程序角2現在angular對象不能從角2起。

這將是真正有用的,如果有人能提出一個可能的方式來達到同樣的角度2.

+0

'Renderer2'? https://angular.io/api/core/Renderer2 – wostex

+0

@wostex我在html中有標記,我想更改類屬性。是否有可能與Renderer2做到這一點 –

回答

3

有幾個方法可以做到這一點:

在組件這樣使用文檔

進口單證:

import {DOCUMENT} from '@angular/platform-browser'; 

像這樣在構造函數中注入它:

constructor(@Inject(DOCUMENT) private document: any) { 

    } 

,並用它來將數據追加任何像這樣的函數內部:

ngOnInit() { 
    let css = ".toolbar-background {background-color: #D3300E !important;}"; 

    this.document.body.innerHTML.append = this.document.body.innerHTML + "<div><style>" + css + "</style></div>"; 
    } 

這裏是工作plunker:

https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/

使用ElementRef

導入ElementRef和像這樣的組件中的ViewChild:

import {ViewChild, ElementRef } from '@angular/core'; 

在你的HTML定義要在其中追加像數據的DIV:使用ViewChild這樣上面的div

<div #styleDiv></div> 

訪問:

@ViewChild('styleDiv') styleDiv:ElementRef; 

和執行所需的附加像這個:

let css = "h2 {color: green;font-size:14px;}"; 
let tmp = "<style>" + css + "</style>"; 
this.styleDiv.nativeElement.insertAdjacentHTML('beforeend',tmp); 

這裏是使用ViewChild和ElementRef的工作蹲跳者: https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/

+0

在闖入者中,我嘗試過: - 'let css =「h2 {color:green;}」; ' 不工作 –

+0

@SuneetJain它正在工作。這裏是讓css =「h2 {color:green;}」的遊擊者; https://embed.plnkr.co/lVRcHNJnxgGsD1iwZJll/ –

+0

您現在已經刪除了.append。用Renderer2可以實現嗎? –

2

可以使用ElementRef和追加的CSS。

構造(myElement:ElementRef){...}